c++ - 在 "char type"模板类中使用字符串文字

标签 c++ templates widechar

我在 C++ 中有一个模板类,它作为 char_type模板参数字符类型,例如char , wchar_t , char32_t , 等等... 该类然后使用 std::basic_string<char_type>在代码中。

然后在类里面的某个地方,我填写了一个转义序列表,例如 "&amp;" .这不起作用,因为取决于模板字符类型,我们需要使用 "&amp;" , L"&amp;" , U"&amp;" ...

有没有办法避免专门用于初始化表的模板函数,例如使用一些标准函数来转换字符串文字?

由于这些是转义序列,因此除了 ASCII 字符外,它们不包含任何其他字符。

最佳答案

我会做以下事情:

template <typename char_type, size_t LENGTH>
constexpr std::basic_string<char_type> literal(const char (&value)[LENGTH])
{
    using string = std::basic_string<char_type>;

    string result{};
    result.reserve(LENGTH);

    std::copy(std::begin(value), std::end(value), std::back_inserter(result));

    return result; // rvo
}

你可以这样使用它:

// Table of escaping sequences
std::basic_string<char_type> escaping_sequences[] =
{
    literal<char_type>("&amp"),
    literal<char_type>("&foo"),
    literal<char_type>("&bar"),
    ...
}

我测试过了in Ideone :

literal<  char  >("test") // result: std::string
literal<char32_t>("test") // result: std::basic_string<char32_t, std::char_traits<char32_t>, std::allocator<char32_t> >
literal<char16_t>("test") // result: std::basic_string<char16_t, std::char_traits<char16_t>, std::allocator<char16_t> >

尚未针对所有字符类型进行测试,但希望对您有所帮助。

编辑 1

糟糕,我刚刚注意到 galinette在我做之前几乎回答了和我一样的问题。我的代码和 galinette 的代码之间的唯一区别是我使用 reserve 分配结果字符串一次,而不是使用 push_back 的自动分配。 del> 在编译时计算字符数,因为使用了 LENGTH 作为模板参数。

编辑2

可以通过将 end 迭代器减 1 来避免最后的空字符问题:

template <typename char_type, size_t LENGTH>
constexpr std::basic_string<char_type> literal(const char (&value)[LENGTH])
{
    using string = std::basic_string<char_type>;

    string result{};
    result.reserve(LENGTH - 1);

    std::copy(std::begin(value), std::end(value) - 1, std::back_inserter(result));

    return result; // rvo
}

或者,使用 std::copy_n 而不是 std::copy:

template <typename char_type, size_t LENGTH>
constexpr std::basic_string<char_type> literal(const char (&value)[LENGTH])
{
    using string = std::basic_string<char_type>;

    string result{};
    result.reserve(LENGTH - 1);

    std::copy_n(std::begin(value), LENGTH - 1, std::back_inserter(result));

    return result; // rvo
}

关于c++ - 在 "char type"模板类中使用字符串文字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32840368/

相关文章:

C++ 自定义单例

c++ - `std::wregex` 是否支持 utf-16/unicode 或仅支持 UCS-2?

c++ - 如何测试字符串是否具有特定的 unicode 字符?

c++ - "Candidate function not viable;"将 C 库移植到 C++ 的问题

c++ - 如何在 C++ 中使用智能指针实现接口(interface)隔离原则?

c# - 我可以用用户输入创建一个 t4 文件吗?

c - C语言中的 "wide character string"是什么?

c# - 用 C++ 编写的存储结构和类在哪里?

c++ - 递归成员函数不能访问自己的变量

c++ - 让函数在不指定模板参数的情况下获取指向模板对象的指针