为什么模板函数只基于返回类型适用于 C++? [英] Why template function only base the return type works on C++?

查看:35
本文介绍了为什么模板函数只基于返回类型适用于 C++?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,重载函数必须包含不同的参数(类型或计数).所以我认为模板函数不应只基于返回类型.但是,以下代码适用于 GCC 6.3.0.

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;
}

构建并运行:

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

C++ 标准是否澄清了这一点?谢谢!

Dose the C++ standard clarify this? Thanks!

推荐答案

不能仅基于返回类型进行重载的原因是,与参数类型不同,返回类型不是函数签名的一部分.不要相信我的话,C++ 标准说了这么多:

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⟩ 名称、参数类型列表和封闭命名空间(如果有)

⟨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)

因此对于 addint 成为签名的一部分.不是因为它是返回类型,而是因为它是模板参数.add 也一样.并且只要签名不同,就可以将它们识别为不同的函数,因此可能会重载在相同的名称上.

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.

这篇关于为什么模板函数只基于返回类型适用于 C++?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆