简体   繁体   English

相同方法签名的模板化和显式参数类型版本

[英]Templated and explicit parameter type versions of same method signature

Consider these are both inside a class declaration: 考虑这些都在类声明中:

template<class V>
bool tryGetValue(const string &key,V& value) const { ... }
bool tryGetValue(const string &key,bool& value) const { ... }

What will the compiler do here? 编译器会在这做什么?

编译器会尽可能选择专用版本。

It will prefer the non-template method. 它更喜欢非模板方法。

From 14.8.3: 从14.8.3开始:

Note also that 13.3.3 specifies that a non-template function will be given preference over a template specialization if the two functions are otherwise equally good candidates for an overload match. 另请注意,如果两个函数在重载匹配方面同样适合,则13.3.3指定非模板函数将优先于模板特化。

And a part from 13.3.3: 并且是13.3.3的一部分:

Given these definitions, a viable function F1 is defined to be a better function than another viable function F2 if for all arguments i, ICSi(F1) is not a worse conversion sequence than ICSi(F2), and then 给定这些定义,可行函数F1被定义为比另一个可行函数F2更好的函数,如果对于所有自变量i,ICSi(F1)不是比ICSi(F2)更差的转换序列,然后

(...) (......)

  • F1 is a non-template function and F2 is a function template specialization, or, if not that, F1是非模板函数,F2是函数模板特化,或者,如果不是,

(...) (......)

The compile will choose the best matching overload. 编译将选择最佳匹配的重载。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM