请考虑以下示例.
#include <string>
template<class CharT, class Traits = std::char_traits<CharT >, class Allocator = std::allocator<CharT >>
void f(const std::basic_string<CharT, Traits, Allocator>& s) {
}
int main() {
f("Hello World!");
}
Run Code Online (Sandbox Code Playgroud)
在编译时,我得到了
不匹配的类型
‘const std::basic_string<_CharT, _Traits, _Alloc>’ and ‘const char []’
为什么编译器不能扣除"CharT"并进行相应的转换basic_string<>?我想只有一个f()签名对任何转换为basic_string<>存在的参数类型有效,是否有解决此问题的方法?
您正在将一个原始字符串传递给您的函数,该函数不是a std::string,是一个字符数组,a const char [].
即使std::string有一个获取char数组的构造函数,在模板argumment推导期间也不会应用隐式类型转换(确切地说就是你遇到的问题).有关该主题的更多信息,请参阅此主题.
有两种可能的解决方案:
将a std::string而不是原始字符串传递给您的函数:
f( std::string( "hello" ) );
Run Code Online (Sandbox Code Playgroud)写一个与原始字符串一起使用的函数重载:
template<typename CHAR_T , std::size_t LENGHT>
void f( const CHAR_T (&string)[LENGTH] )
{
f( std::string( string ) ); //Just wrap the call to not duplicate code.
}
Run Code Online (Sandbox Code Playgroud)