Как написать шаблоны с std :: basic_string для типов символов C? - PullRequest
0 голосов
/ 04 мая 2018

Тип для 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?

...