说我有一堂这样的课
template<typename CharT>
class basic_class
{
public:
using char_type = CharT;
using string_type = std::basic_string<CharT>;
private:
const char_type ch = '?';
const string_type str{"How to init"};
};
可以将其设为char,但不能用于wchar_t。
- How can i do this ?
编辑:
我决定编写一个将char和string形式转换为各种类型的函数,例如
template<typename To>
constexpr To to_type(char val)
{}
template<>
constexpr char to_type<char>(char val)
{
return val;
}
template<>
constexpr wchar_t to_type<wchar_t>(char val)
{
//....
}
template<>
constexpr char16_t to_type<char16_t>(char val)
{
//....
}
template<>
constexpr char32_t to_type<char32_t>(char val)
{
//....
}
和template<typename To>
constexpr To to_type(std::string val)
{}
template<>
constexpr std::string to_type<std::string>(std::string val)
{
return val;
}
template<>
constexpr std::wstring to_type<std::wstring>(std::string val)
{
//....
}
template<>
constexpr std::u16string to_type<std::u16string>(std::string val)
{
//....
}
template<>
constexpr std::u32string to_type<std::u32string>(std::string val)
{
//....
}
然后我会像这样使用template<typename CharT>
class basic_class
{
public:
using char_type = CharT;
using string_type = std::basic_string<CharT>;
private:
const char_type ch = to_type<char_type>( '?' );
const string_type str{ to_type<string_type>( "How to init" ) };
};
在if语句中if ( ch == to_type<char_type>('?') )
{
//....
}
if ( str == to_type<string_type>("How to init") )
{
//....
}
- How to convert char and std::string other types ?
欢迎所有建议,谢谢。
最佳答案
您可以定义一个返回正确类型值的函数:
template<typename CharT>
class basic_class
{
public:
using char_type = CharT;
using string_type = std::basic_string<CharT>;
private:
constexpr auto getInitString() {
if constexpr (is_same<CharT, wchar_t>::value) {
return L"How to init";
}
else {
return "How to init";
}
}
const char_type ch = '?';
const string_type str{getInitString()};
};
这将适用于C++ 17,但在较早的版本上会有些棘手。另一种方法是从某物复制:
std::string_view initString = "How to init"sv;
template<typename CharT>
class basic_class
{
public:
using char_type = CharT;
using string_type = std::basic_string<CharT>;
private:
const char_type ch = '?';
const string_type str{initString.begin(), initString.end()};
};
关于c++ - 如何初始化未知的字符串类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63239555/