Sign in to follow this  
mrrolf810p

template checking

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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this