templates help

L

lallous

Hello,

I would like to define a template as:

template <class T, class R> void func(T &r)
{
r = (T)((R)r);
}

For example:
double d;
func<double, int>(d);
this would do: (double)((int)d)

1)Is this a good way to achieve this?
I don't want to use any instance of "R" but just use it to cast.

2)
How can I set that "R" is by default a "long" type?
It seems that <class T, class R = long> will only work w/ classes and not
function templates.

Regards,
Elias
 
V

Victor Bazarov

lallous said:
I would like to define a template as:

template <class T, class R> void func(T &r)
{
r = (T)((R)r);
}

For example:
double d;
func<double, int>(d);
this would do: (double)((int)d)

1)Is this a good way to achieve this?
I don't want to use any instance of "R" but just use it to cast.

No, type casts cannot be used as a source of information for template
type derivation. You could do

template<class R, class T> void func(T &r)
{
r = T(R(r));
}

...
double d;
...
2)
How can I set that "R" is by default a "long" type?
It seems that <class T, class R = long> will only work w/ classes and not
function templates.

I am not sure what you mean by "will only work". Default template
arguments are allowed for functions too.

Victor
 

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
474,145
Messages
2,570,828
Members
47,374
Latest member
anuragag27

Latest Threads

Top