如何使用std :: basic_string为C字符类型编写模板?

时间:2018-05-04 16:01:06

标签: c++ templates stdstring

无法从std::basic_stringchar推断出wchar_tconst 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是否有更优雅的解决方案?

0 个答案:

没有答案