If you really need to have two function templates with the same names, the same list of parameters, but with different types of return values, you have no choice but to distinguish them by specifying the type of the parameter returned by the template:
template <typename R, typename T> R foo(T);
IIRC there is a specialized specification of function templates in C ++ 11, although I could not find anything about this in the standard. If there is, this should work:
//partial function template specializations: C++11 only! template <typename T> long foo<long, T>(T) { std::cout << "long" << std::endl; return 0; } template<typename T> char foo<char, T>(T) { std::cout << "char" << std::endl; return '\0'; }
Or else, in C ++ 03:
template <typename R, typename T> struct FooImpl; template <typename T> struct FooImpl<long, T> { static long doIt(T) { std::cout << "long" << std::endl; return 0; } }; template <typename T> struct FooImpl<char, T> { static char doIt(T) { std::cout << "char" << std::endl; return '\0'; } }; template <typename R, typename T> R foo(T t) { return FooImpl<R, T>::doIt(t); }
In both cases, your main file will look like this:
int main() { double d = 0.0; long n = foo<long>(d);
source share