在:
#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/