Implicit conversion constructor with template classes

F

flopbucket

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.
 
T

Tom Widmer

flopbucket said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,014
Latest member
BiancaFix3

Latest Threads

Top