无法从std::basic_string
或char
推断出wchar_t
(const char*
,const wchar_t*
,...)的类型:
#include <string>
template <class chTy>
void f(std::basic_string<chTy> s, chTy c) {}
int main()
{
const char* narrowCS = "";
char narrowC = {};
const wchar_t* wideCS = L"";
wchar_t wideC = {};
std::string narrowS;
std::wstring wideS;
// The calls with C string arguments will throw in VS2017:
// - C2672: no matching overloaded function found
// - C2784: could not deduce template argument for 'std::basic_string<_Elem,std::char_traits<_Elem>,std::allocator<_Ty>>' from 'const char *'
//f(narrowCS, narrowC);
//f(wideCS, wideC);
f(narrowS, narrowC);
f(wideS, wideC);
}
两种变体可以解决这个问题:
template <class chTy>
void f(std::basic_string<chTy> s, chTy c) {}
template <class chTy>
void f(const chTy* s, chTy c) { f(std::basic_string<chTy>(s), c); }
或使用隐式构造s
的重载void f(std::string s, char c) {}
void f(std::wstring s, wchar_t c) {}
使用std::basic_string
是否有更优雅的解决方案?