[英]Templated and explicit parameter type versions of same method signature
考虑这些都在类声明中:
template<class V>
bool tryGetValue(const string &key,V& value) const { ... }
bool tryGetValue(const string &key,bool& value) const { ... }
编译器会在这做什么?
编译器会尽可能选择专用版本。
它更喜欢非模板方法。
从14.8.3开始:
另请注意,如果两个函数在重载匹配方面同样适合,则13.3.3指定非模板函数将优先于模板特化。
并且是13.3.3的一部分:
给定这些定义,可行函数F1被定义为比另一个可行函数F2更好的函数,如果对于所有自变量i,ICSi(F1)不是比ICSi(F2)更差的转换序列,然后
(......)
- F1是非模板函数,F2是函数模板特化,或者,如果不是,
(......)
编译将选择最佳匹配的重载。
template<class V>
bool tryGetValue(const std::string &key,V& value) {
return false;
}
// Overload (no specilaization)
bool tryGetValue(const std::string &key,bool& value) {
return true;
}
int main()
{
std::string s = "Hello";
int i = 1;
bool b = true;
std::cout
<< "Template: "
<< ((tryGetValue(s, i) == false) ? "Success" : "Failure") << std::endl;
std::cout
<< "No Template: " << (tryGetValue(s, b) ? "Success" : "Failure") << std::endl;
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.