gpt4 book ai didi

c++ - 按返回类型重载函数模板

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:06:31 25 4
gpt4 key购买 nike

我无意中发现以下两个模板可以被重载(不会导致名称重定义错误),我认为这是违反直觉的。

template<typename T>
void func(T) {}

template<typename T>
int func(T) {return 0;}

来自cppreference.com,有一段相关的内容:

When an expression that uses type or non-type template parameters appears in the function parameter list or in the return type, that expression remains a part of the function template signature for the purpose of overloading:

但是这两个函数的返回类型不包括T。谁能给我解释一下?

最佳答案

您引用的段落无关紧要。

有一个特殊规则可以防止仅返回类型不同的非模板函数被重载(来自标准 [over.load]/2.1):

Function declarations that differ only in the return type, the exception specification, or both cannot be overloaded.

所以如果这样的声明存在(即使程序没有调用它们),程序就是病式的。但是,此规则既不适用于函数模板,也不适用于根据 [over.load]/1 为重载解析目的而合成的模板特化。

Not all function declarations can be overloaded. Those that cannot be overloaded are specified here. A program is ill-formed if it contains two such non-overloadable declarations in the same scope. [ Note: This restriction applies to explicit declarations in a scope, and between such declarations and declarations made through a using-declaration. It does not apply to sets of functions fabricated as a result of name lookup (e.g., because of using-directives) or overload resolution (e.g., for operator functions). — end note ]

所以这两个模板可以很好的重载。

但是,正如 Dean Seo 在他的回答中所说,如果您尝试调用 func,由于重载解析的歧义,程序将是格式错误的。

关于c++ - 按返回类型重载函数模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49222651/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com