• Advertisement
Sign in to follow this  

template checking

This topic is 4982 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Is there a way to check the type of a template? For example template <class T> Foo(T x){ if(T is type (int)) .... if(T is type (float)) .... } I need to check because I have constants I need to assign depending on the type. Thanks

Share this post


Link to post
Share on other sites
Advertisement
Probably better to use a trait class of some sort


template<typename T>
struct trait{
static T value(){
return 1.0;
}
};

template<>
struct trait<float>{
static float value(){
return 1.0f;
}
};

template<>
struct trait<int>{
static int value(){
return 1;
}
};


//then get the valu by using the trait class
template<typename T>
void myfunc()
{
T value = trait<T>::value();
...
}




Hope that helps :)

Share this post


Link to post
Share on other sites
Firstly, I expect your not using templates correctly if you need to do that, so you may want to consider that. In answer to your question though, I think you're looking for run-time type identification (RTTI) and you'll need to use typeid, though I don't remember the exact syntax.

tj963

Share this post


Link to post
Share on other sites
I was trying to make a generic Image class for opengl. I was running into problems when I has to specify the data type with an opengl constant.

I'll give the trait class a try.
Thanks!

Share this post


Link to post
Share on other sites
If you really wanted the if else syntax, you could use specialization in a different way, a little something like this


#include<iostream>


template<bool isint = false, bool isfloat = false, bool isdouble = false>
struct traits_base{
static const bool is_int = isint;
static const bool is_float = isfloat;
static const bool is_double = isdouble;
};

template<typename T>struct traits : traits_base<>{};

//specializations
template<> struct traits<int> : traits_base<true>{};
template<> struct traits<float> : traits_base<false, true>{};
template<> struct traits<double> : traits_base<false, false, true>{};

template<typename T>
void print(){

if(traits<T>::is_int)
std::cout <<" int\n";
else if(traits<T>::is_float)
std::cout <<" is float\n";
else if(traits<T>::is_double)
std::cout <<" is_double\n";
else
std::cout <<" unknown\n";
}

int main(){
print<int>();
print<float>();
print<double>();
print<char>();
}




You could just extend it for the types you need.

Hope that helps :)

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement