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!
Templates are a feature of the C++ programming language that allows functions and classes to operate with generic types. This allows a function or class to work on many different data types without being rewritten for each one.
main cannot be a function template; it must be a function.
The template function works for int and char, but not float and string.
Why we use :: template-template parameter? Explanation: It is used to adapt a policy into binary ones.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With