By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
445,797 Members | 1,848 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 445,797 IT Pros & Developers. It's quick & easy.

Implicit conversion constructor with template classes

P: n/a
Hi,

If I have:

template<class T>
class X
{
.....
};

then:

template<class U>
class Y
{
public:
typedef X<U> NormalType;
typedef X<const U> ConstType;

NormalType foo() { return NormalType(); }
};

How can I (or can I?) have conversion from NormalType to ConstType so
the following would work:

Y<int> bar;
ConstType i = bar.foo();

Can I have a constructor in Y like "Y(const Y<const T>&)" to provide
implicit conversion? If I do something in Y like:

template<class Z>
Y(const Z&)

That would apply to any type and try to convert, wouldnt it?

Is there a way I can specify I can accept a type "const T" when the
template is instantiated with just T?
Thanks for any tips.

Jun 25 '06 #1
Share this Question
Share on Google+
1 Reply


P: n/a
flopbucket wrote:
Hi,

If I have:

template<class T>
class X
{
....
};

then:

template<class U>
class Y
{
public:
typedef X<U> NormalType;
typedef X<const U> ConstType;

NormalType foo() { return NormalType(); }
};

How can I (or can I?) have conversion from NormalType to ConstType so
the following would work:

Y<int> bar;
ConstType i = bar.foo();
Presumably you can modify Y's code. Can you modify X's too?
Can I have a constructor in Y like "Y(const Y<const T>&)" to provide
implicit conversion? If I do something in Y like:

template<class Z>
Y(const Z&)

That would apply to any type and try to convert, wouldnt it?
Yes, but it would convert it to a Y, not an X.
Is there a way I can specify I can accept a type "const T" when the
template is instantiated with just T?


You have to be careful, since the type obviously needs to work with
const. In your case, something like this should work:

template <class T>
class X
{
public:
X(X<const T> const&); //construct from const.
};

template <class T>
class X<const T>
{
//no const T constructor
};

You could move common functionality into a base class to avoid excessive
repetition.

Tom
Jun 26 '06 #2

This discussion thread is closed

Replies have been disabled for this discussion.