c++ - 不会匹配模板函数

标签 c++ templates

在:

#include <string>

void f( char const*, char const* = "" ) {
}

template<class StringType1,class StringType2> inline
void g( StringType1 const &s1, StringType2 const &s2 = "" ) {
  f( s1.c_str(), s2.c_str() );
}

template<class StringType> inline
void h( StringType const &s1, StringType const &s2 = "" ) {
  f( s1.c_str(), s2.c_str() );
}

int main() {             
  std::string s;
  g( s ); // error: no matching function for call to ‘g(std::string&)’
  h( s ); // OK
  return 0;
}

编译器不匹配对 g() 的调用,因为它有 2 个模板参数,但它匹配 h() 就好了。为什么?

仅供引用:我的代码库实际上使用了几个高度特化的字符串类,所以我想允许最大的灵 active ,其中第一个和第二个参数可能是不同的字符串类型。

最佳答案

编译器不知道 StringType2 应该是什么。你需要用类似的东西来调用它:

   g<std::string, std::string>( s );

让它正常工作。

关于c++ - 不会匹配模板函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4749790/

相关文章:

c++ - 如何将有向图(邻接表)传递给 Dijkstra 算法 boost 以找到最短路径?

c++ - Boost预处理器多个模板类生成

c++ - 具有相同名称和不同模板参数的两个结构如何工作

c++ - 为什么 make_optional 不适用于文件流?

c++ - 函数模板和迭代器

c++ - C/C++ : Inherent ambiguity of "\xNNN" format in literal strings

c++ - 根据模板参数不同的基类

c++ - 什么时候使用openGL将数据发送到GPU

c++ - 模板和 std::numeric_limits

c++ - 为什么类型推导一次失败,而在两种非常相似的情况下又一次成功?