问题
Mooing Duck makes a comment here that "One function can't return multiple types. However, you can specialize or delegate to overloads, which works fine."
I started thinking about that, and I'm trying to figure out, how is this legal code:
template <typename T>
T initialize(){ return T(13); }
When called with:
auto foo = initialize<int>();
auto bar = initialize<float>();
Doesn't that translate to 2 functions of the same name overloaded by return-type only?
回答1:
It's not an overload, it's a specialization. They are different mechanisms (in fact mixing the two can lead to confusion, because overloads are resolved before specializations are considered -- see this Sutter's Mill article for example: http://www.gotw.ca/publications/mill17.htm).
回答2:
Here's an example of the disallowed return value only overload:
int initialize();
float initialize();
OTOH, given the primary template definition
template <typename T>
T initialize(){ return T(13);}
Quoting from here
In order to compile a function call, the compiler must first perform name lookup, which, for functions, may involve argument-dependent lookup, and for function templates may be followed by template argument deduction. If these steps produce more than one candidate function, then overload resolution is performed to select the function that will actually be called.
initialize<int>
and initialize<float>
are simply two different instantiations of the said template. They are two different functions and would not be part of the same list of potential overload resolution candidates.
来源:https://stackoverflow.com/questions/28906771/overloading-template-by-return-type