S
Sachin Garg
I was trying something with templates in C++, can't figure out if it is
possible.
Can I check in a function what template parameter was passed, and then
decide what to do?
for example...
I have two simple types:
struct x {int a, b, c};
struct y {int x};
A template class is defined with
template<class T>
then in one of the member functions, I want to do
if(T==x) { do something with a, b and c}
if(T==y) { do something with x}
(These ifs need to be resolved at compile time, else the code wont
compile.)
Something similar can be done through template specialization, but I
was hoping if such if/else is possible.
I can do if(typeid(T ) == typeid(x))
but this is resolved at run time... I want something which gets
resolved at compile time. To avoid the performance hit.
I can think of a work around....
template<int t_id, class T>
and then in code...
if(t_id==x_id) { do stuff for x}
if(t_id==y_id) { do stuff for y}
(here x_id and y_id are constants)
Only problem is that now t_id and T essentially mean the same thing, so
its kinda redundant to specify both. But this should work
Templates can have if else on value parametres which get solved at
compile time, I was just hoping if it can do that with type parameters
too.
Technically this seems to be possible. What will be the best option in
this case, any alternates you can suggest.
Sachin Garg [India]
www.sachingarg.com | www.c10n.info
possible.
Can I check in a function what template parameter was passed, and then
decide what to do?
for example...
I have two simple types:
struct x {int a, b, c};
struct y {int x};
A template class is defined with
template<class T>
then in one of the member functions, I want to do
if(T==x) { do something with a, b and c}
if(T==y) { do something with x}
(These ifs need to be resolved at compile time, else the code wont
compile.)
Something similar can be done through template specialization, but I
was hoping if such if/else is possible.
I can do if(typeid(T ) == typeid(x))
but this is resolved at run time... I want something which gets
resolved at compile time. To avoid the performance hit.
I can think of a work around....
template<int t_id, class T>
and then in code...
if(t_id==x_id) { do stuff for x}
if(t_id==y_id) { do stuff for y}
(here x_id and y_id are constants)
Only problem is that now t_id and T essentially mean the same thing, so
its kinda redundant to specify both. But this should work
Templates can have if else on value parametres which get solved at
compile time, I was just hoping if it can do that with type parameters
too.
Technically this seems to be possible. What will be the best option in
this case, any alternates you can suggest.
Sachin Garg [India]
www.sachingarg.com | www.c10n.info