【发布时间】:2020-11-24 02:48:58
【问题描述】:
假设我有这样的课程
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不行。
- 我该怎么做?
编辑:
我决定编写一个函数,将表单 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") )
{
//....
}
- 如何将char和std::string转换成其他类型?
欢迎所有建议,提前致谢。
【问题讨论】:
-
是否必须将其初始化为特定的硬编码字符串?可以将字符串传递给
basic_class构造函数吗? -
感谢您的回复,但我知道我只想初始化它的字符串的值。
-
或许你可以通过专业化来解决?但请记住,“字符”类型比
char和wchar_t更多。 -
但是在 if 语句中我还有更多的字符串要使用吗?我应该所有都是成本,这是个好主意吗?
-
@某程序员老兄你能看到更新问题吗?
标签: c++ string class templates