Saddle Point
Saddle Point

Reputation: 3225

How to write a template function to create char/wchar_t strings given const char*?

I'd like to write function to create char/wchar_t strings given const char* ('narrow' string literals).

For example, something like

template<typename T>
std::basic_string<T> test(const char* str) {
    ///
}

So that I can use

std::string a = test<char>("haha");

or

std::wstring b = test<wchar_t>("哈哈"); // NOT L"哈哈"

to create strings based on template arguments.

I known it would be easy if the function argument is const T* str. But I can't figure it out when it is const char* str. And I think some conversion must be performed.

Thanks in advance.

Upvotes: 1

Views: 1095

Answers (1)

Serge Ballesta
Serge Ballesta

Reputation: 149075

It not that hard, you have just to write explicit specializations for your template function. The major drawback here is that you will have to alway pass the type argument, because no template deduction can occur here: both specializations have exactly same parameters: one const char * parameter.

That being said, you can write:

template<typename T>
std::basic_string<T> test(const char* str) {
    ///
}

template <>
std::basic_string<char> test<char>(const char *str) {
    // generate a std::string
}

template <>
std::basic_string<wchar_t> test<wchar_t>(const char *str) {
    // generate a std::wstring
}

But you will have to use them that way:

std::string str = test<char>("haha");
std::wstring wstr = test<wchar_t>("哈哈");

Upvotes: 2

Related Questions