c++ - 模板参数的隐式转换规则

标签 c++ templates overloading

如果您重载一个函数,然后使用与其中一个重载完全匹配的参数调用它

int f(int){return 3;}
int f(bool){return 4;}
...        //inside main()
f(1);      //Calls f(int)

编译器在尝试任何隐式转换之前简单地选择这个(完美)匹配。但是我一直在尝试重载函数 tempĺate,如

template <bool veracity>
int f(){return 1;}

template <int amount>
int f(){return 2;}

...        //inside main()
f<1>();

但是编译器一直提示对重载的 f() 的调用不明确,说明它可能是 f<true>()f<1>() .编译器不应该只选择完美匹配,而不是尝试将 1 转换为 true 吗?

我的印象是模板参数的隐式转换实际上比函数参数的隐式转换更具限制性。有没有办法解决这个问题?

最佳答案

你提供的参数不是类型,它是一个值,所以规则有点不同——你需要对非类型参数应用规则。对于非类型参数,允许隐式转换。 §14.3.2/5:

The following conversions are performed on each expression used as a non-type template-argument. If a non-type template-argument cannot be converted to the type of the corresponding template-parameter then the program is ill-formed.

— For a non-type template-parameter of integral or enumeration type, conversions permitted in a converted constant expression (5.19) are applied.

在 C++03 中,措辞略有不同,但效果基本相同(也是 §14.3.2/5):

— for a non-type template-parameter of integral or enumeration type, integral promotions (4.5) and integral conversions (4.7) are applied.

无论哪种方式,由于 1 既是 int 又可以隐式转换为 bool,因此您的调用不明确。

关于c++ - 模板参数的隐式转换规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10031397/

相关文章:

f# - 非惯用的全局运算符重载如何工作?

c++ - 分配/释放大量小对象的策略

c++ - POS 终端应用程序开发 - SDK、编程语言、模式、IDE

c++ - 为什么人们不缩进 C++ 访问说明符/case 语句?

c++ - SFINAE 重载,必须考虑哪些规则

templates - 导入的包在 Play 中不可用!框架模板

templates - 模板内的 XSL 循环

c# - 如何处理重载方法签名的冲突?

java - 如何编写没有方法重载的通用 Java API

java - C++ 中 BufferedImage 的替代