Search code examples
c++templates

Overriding return type in function template specialization


I would like to specialize a function template such that the return type changes depending on the type of the template argument.

class ReturnTypeSpecialization
{
public:
    template<typename T>
    T Item();
};

// Normally just return the template type
template<typename T>
T ReturnTypeSpecialization::Item() { ... }

// When a float is specified, return an int
// This doesn't work:
template<float>
int ReturnTypeSpecialization::Item() { ... }

Is this possible? I can't use C++11.


Solution

  • Since the specialization has to agree with the base template on the return type, you can make it so by adding a "return type trait", a struct you can specialize and draw the true return type from:

    // in the normal case, just the identity
    template<class T>
    struct item_return{ typedef T type; };
    
    template<class T>
    typename item_return<T>::type item();
    
    template<>
    struct item_return<float>{ typedef int type; };
    template<>
    int item<float>();
    

    Live example.

    Note that you might want to stick to the following, so you only need to update the return-type in the item_return specialization.

    template<>
    item_return<float>::type foo<float>(){ ... }
    // note: No `typename` needed, because `float` is not a dependent type