Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

templates

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!

like image 826
sfz Avatar asked Jan 15 '19 08:01

sfz


People also ask

Why template is used in C?

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.

Can we use template in main function?

main cannot be a function template; it must be a function.

Does function template work with string?

The template function works for int and char, but not float and string.

Why do we use template template parameter?

Why we use :: template-template parameter? Explanation: It is used to adapt a policy into binary ones.


1 Answers

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.

like image 194
StoryTeller - Unslander Monica Avatar answered Nov 15 '22 14:11

StoryTeller - Unslander Monica