现在我有两个函数执行完全相同的解析工作,一个用于 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/