如果您重载一个函数,然后使用与其中一个重载完全匹配的参数调用它
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/