c++ - 如何初始化未知的字符串类型?

标签 c++ string class templates

说我有一堂这样的课

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。
  1. 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") )
{
  //....
}
  1. 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/

相关文章:

c++ - 无法实例化类

javascript - 类继承 - 添加参数而不重写父构造函数参数

jquery - 如何在两个表行之间插入另一个表行?

c++ - 为什么 FFMPEG 屏幕录像机输出仅显示绿屏?

c# - 字符串没有像我期望的那样连接

c++ - 使用 Luajit 时,使用 FFI 还是使用普通的 lua 绑定(bind)更好?

c++ - 如何将字符串 vector 传递给 execv

java - 字体度量字符串宽度与字符串长度

c++ - C++ 的混合类型、可变长度参数列表(varargin、*args、...)

c++ - C++ 标准对堆栈溢出有何规定?