type convertion between template

K

kaikai

Hi, I've got a problem while trying to make my source code clean.

In a template:

template<typename T>
class A
{
public:
T data;
};

may I write a type convertion operator that can convert A<T1> to A<T2>
?
I guess it will be something like this, but failed I am.

template<typename T>
class A
{
public:
T data;
template<typename T2> operator A<T2> () const
{
A<T2> temp;
temp.data = (T2)data;
return temp;
}
};

Sincerely,

kaikai
 
L

Luke Meyers

kaikai said:
may I write a type convertion operator that can convert A<T1> to A<T2>
?

Yes. An instantiated template is a type, and you can use it wherever
you would use a type, including in a conversion operator.
I guess it will be something like this, but failed I am.

template<typename T>
class A
{
public:
T data;
template<typename T2> operator A<T2> () const
{
A<T2> temp;
temp.data = (T2)data;
return temp;
}
};

Works fine for me. What's the problem on your end?

By the way, don't use those old C-style casts! They're very unsafe.
Use static_cast.

Luke
 
K

kaikai

Luke said:
Yes. An instantiated template is a type, and you can use it wherever
you would use a type, including in a conversion operator.


Works fine for me. What's the problem on your end?

I got error c2440 under msvc++6 sp6,

error C2440: 'type cast' : cannot convert from 'struct _Point2<int>' to
'struct _Point2<float>'
No constructor could take the source type, or constructor
overload resolution was ambiguous

cods:
template< typename T >
struct _Point2
{
T x, y;
template< typename T2 >
operator _Point2<T2> () const
{
_Point2<T2> t;
t.x = T2(x);
t.y = T2(y);
return t;
}
};

// in a function...
Point2f a;
Point2i b;
a = Point2f(b); // here got the error
By the way, don't use those old C-style casts! They're very unsafe.
Use static_cast.

Luke

kaikai
 
L

Luke Meyers

kaikai said:
I got error c2440 under msvc++6 sp6,

Well, there's your problem right there. MSVC 6 has crappy support for
real template programming. Sorry, but you're stuck. Download a better
compiler, there are many excellent ones freely available. And the MSVC
6 IDE is pretty dated by now, too...

Luke
 
K

kaikai

Luke said:
Well, there's your problem right there. MSVC 6 has crappy support for
real template programming. Sorry, but you're stuck. Download a better
compiler, there are many excellent ones freely available. And the MSVC
6 IDE is pretty dated by now, too...

Luke

OIC, thank you :)

kaikai
 

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

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top