c++ - 一个处理 char* 和 wchar_t* 的函数

标签 c++ templates char wchar-t wchar

现在我有两个函数执行完全相同的解析工作,一个用于 char*和一个 wchar_t* .我只想拥有一个功能,这样我只需要更改一次(为了保持一致性)。将整个字符串转换为 char*wchar_t*不是一个选项,因为字符串可能很长并且不应在内存中重复。

这两个函数的唯一区别是我必须使用 'a'对于 char*L'a'对于 wchar_t* .

有没有办法(例如,使用模板元编程)来实现这一目标?

最佳答案

它可以用 traits 而不用宏来完成,但它很麻烦而且容易出错,因为每个字符或字符串文字都必须在两个模板特化中重复。不过,C++11 的 auto 有点帮助:

#include <string>
#include <iostream>

template <class CharType>
struct MyTraits
{
};

template <>
struct MyTraits<char>
{
    static auto constexpr a = 'a';
    static auto constexpr foo = "foo";
    static auto constexpr lb = '\n';
};

template <>
struct MyTraits<wchar_t>
{
    static auto constexpr a = L'a';
    static auto constexpr foo = L"foo";
    static auto constexpr lb = L'\n';
};

template <class CharType>
void f(std::basic_ostream<CharType>& os, std::basic_string<CharType> const& s)
{
    os << s << MyTraits<CharType>::a << MyTraits<CharType>::foo << MyTraits<CharType>::lb;
}

int main()
{
    f(std::cout, std::string("bar"));
    f(std::wcout, std::wstring(L"bar"));
}

一个长期的解决方案是摆脱支持这两种字符类型的必要性(或功能?)。

关于c++ - 一个处理 char* 和 wchar_t* 的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35748234/

相关文章:

c++ - 函数定义中 '*' 标记之前的预期构造函数、析构函数或类型转换

c++ - 相同类型之间的无效转换

c - 如果前一个数组是同一位置的字符,则填充数组

c++ - 在 map 元素上使用 for_each

c++ - 如何使用 new 在 C++ 中创建数组并初始化每个元素?

c++ - 双模板函数重载失败

更改 char 指针数组中的字符串

c++ - C++中的字符赋值

c++ - 使用 read() 时,TCP 流中包含哪些 header ?

c++ - 使用 std::sort 查找 std::vector 中的前 N ​​个项目