Search code examples
c++templatestypesreturnoverloading

Could C++ template function overload on return parameter?


With same template declaration, is it possible to differ two functions with same name, same param list, but different return type?

template <class T>
int f()...

template <class T>
short f()...

Or, need some special code to achieve this?

Thanks.


Solution

  • You can indeed have function templates with same name, same parameter types, and same return type (but you cannot for regular functions).

    template <class T>
    int f() {/*..*/}
    
    template <class T>
    short f() {/*..*/}
    

    But then their usage is not really easy/fine:

    auto i = static_cast<int(*)()>(&f<float>)(); // Call int f<float>
    auto s = static_cast<short(*)()>(&f<float>)(); // Call short f<float>