tag dispatching c++




Switch passed type from template (3)

Is it possible in C++ to check the type passed into a template function? For example:

template <typename T>
void Foo()
{
   if (typeof(SomeClass) == T)
      ...;
   else if (typeof(SomeClass2) == T)
      ...;
}

If you want to do something specific based on the type, specialize the template:

template <typename T>
void Foo() { }

template <>
void Foo<SomeClass>() { }

template <> 
void Foo<SomeClass2>() { }

// etc.

(You don't actually want to specialize the function template, though; this is for exposition only. You'll either want to overload the template if you can, or delegate to a specialized class template. For more on why and how to avoid specializing function templates, read Herb Sutter's Why Not Specialize Function Templates?)


No, however you can use partial specialization :

template<typename T>
struct Bar { static void foo(); };
template<typename T>
template<> inline void Bar<T>::foo() {
//generic
}
template<> inline void Bar<int>::foo() {
//stuff for int
}
template<> inline void Bar<QString>::foo() {
//QString
}

Edit Yes with type traits, however it's not really needed. Edit 2 type_traits example.

#include <type_traits>
template<typename T> void foo() {
    using std::is_same;
    if<is_same<T, T2>::value || is_same<T, T1>::value) { 
        /* stuff */
    }
}

Yes. You will have to use type traits. For example:

#include <boost/type_traits/is_same.hpp>

template <typename T>
void Foo ()
{
   if ((boost::is_same<T, SomeClass>::value))
      ...;
   else if ((boost::is_same<T, SomeClass2>::value))
      ...;
}

Depending on what you are trying to achieve, using template specialization might be much better choice.

Also, you can use enable_if/disable_if to conditionally enable/disable certain functions/methods. Combining this with type traits will allow, for example, using one function for one set of types and another function for another set of types.





types