Why template function only base the return type works on C++?

  • A+
Category:Languages

As I know, overloading functions must contain different arguments(type or count). So I think the template function should not only base on the return type. However the following code works on GCC 6.3.0.

#include <iostream> using namespace std;  template<typename T> T add(double a, double b) {     return static_cast<T>(a + b);  }  int main() {     cout << add<int>(1.1, 1) << endl;     cout << add<double>(1.1, 1) << endl;     return 0; } 

Build and run:

g++ -g -o test test.cpp ./test 2 2.1 

Dose the C++ standard clarify this? Thanks!

 


The reason you cannot overload based on return type alone is that the return type is not part of a functions signature, unlike the parameter types. Don't take my word for it, the C++ standard says as much:

[defns.signature]

⟨function⟩ name, parameter-type-list, and enclosing namespace (if any)

[ Note: Signatures are used as a basis for name mangling and linking. — end note ]

But for function template specializations, be they generated implicitly or explicitly, the signature contains the argument(s):

[defns.signature.spec]

⟨function template specialization⟩ signature of the template of which it is a specialization and its template arguments (whether explicitly specified or deduced)

So for add<int>, the int becomes part of the signature. Not because it's the return type, but because it's the template argument. Same for add<double>. And so long as the signatures are different, those can be identified as different functions, and therefore may be overloaded on the same name.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: