Search code examples
c++templatesgeneric-programming

Different type based on template type


I have ::Class1 and ::Class2, I'd like to create template function that gets either first or second one and then based on selected class use other classes defined in different namespace i.e. NameSpace::Class1, NameSpace::Class2. Is there way to do it in C++?

For example:

namespace NameSpace 
{ 
    class Class1 {}; class Class2 {}; 
} 

template <class T> // example Class1 or Class2 
void f(T object) { 
    NameSpace::T obj; // Something like this, but it doesn't work 
}

Solution

  • You can specialize a struct to map one type to another

    template <typename T>
    struct FromType {};
    
    template <>
    struct FromType<Class1>
    {
        typedef ns::Class1 type;
    }
    
    template <>
    struct FromType<Class2>
    {
        typedef ns::Class2 type;
    }
    

    This can then be used in a template function by referring to the resulting type as

    typename FromType<T>::type
    

    Note that this will also give a compile error if you attempt to use a type other than Class1 or Class2.