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

时间:2013-09-19 15:49:56

标签: c++ visual-c++ visual-studio-2005

考虑这些都在类声明中:

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

编译器在这做什么?

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

它更喜欢非模板方法。

从14.8.3开始:

  

另请注意,13.3.3指定将给出非模板函数   如果两个函数同样适合重载匹配,则优先于模板特化。

13.3.3中的一部分:

  

鉴于这些定义,如果对于所有参数i,可行函数F1被定义为比另一个可行函数F2更好的函数,ICSi(F1)不是比ICSi(F2)更差的转换序列,然后

     

(...)

     
      
  • F1是非模板函数,F2是函数模板特化,或者,如果不是,
  •   
     

(...)

答案 2 :(得分:0)

编译将选择最佳匹配的重载。

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;
}
相关问题