【发布时间】:2015-11-03 23:43:25
【问题描述】:
我的代码可以创建一个字符或字符串常量,它可以是 char 或 wchar_t 类型。这使得创建模板函数成为可能,这些函数既可以使用字符类型,也可以使用字符或字符串常量。到目前为止,我提出的解决方案如下。
template<typename CharType>
CharType CharConstantOfType(const char c, const wchar_t w);
template<>
char CharConstantOfType<char>(const char c, const wchar_t /*w*/)
{
return c;
}
template<>
wchar_t CharConstantOfType<wchar_t>(const char /*c*/, const wchar_t w)
{
return w;
}
template<typename CharType>
const CharType* StringConstantOfType(const char* c, const wchar_t* w);
template<>
const char* StringConstantOfType<char>(const char* c, const wchar_t* /*w*/)
{
return c;
}
template<>
const wchar_t* StringConstantOfType<wchar_t>(const char* /*c*/, const wchar_t* w)
{
return w;
}
这些模板函数要求您通过提供常量的两个版本来复制常量。为了解决这些问题,我创建了以下宏。
#define _TOWSTRING(x) L##x
#define TOWSTRING(x) _TOWSTRING(x)
#define CHAR_CONSTANT(TYPE, STRING) CharConstantOfType<TYPE>(STRING, TOWSTRING(STRING))
#define STRING_CONSTANT(TYPE, STRING) StringConstantOfType<TYPE>(STRING, TOWSTRING(STRING))
我想消除宏。我想知道像 Boost MPL 库这样的东西是否可以实现这一点。
这些宏的一个可能用途是编写一个模板函数来确定字符串是否包含制表符,如下所示。
template<typename CharType>
bool hasTab(const std::basic_string<CharType>& str)
{
typedef std::basic_string<CharType> string_type;
const CharType TabChar = CHAR_CONSTANT(CharType, '\t');
return (str.find(TabChar) != string_type::npos);
}
【问题讨论】:
-
如果你想要的话,我认为模板不允许你在编译时从另一个字符串文字中创建一个字符串文字。但我可能弄错了(如果是这样的话,我很想知道它是如何完成的)。
-
+Caninonos 我想做的是创建一个可以是 char 或 wchar_t 的单个字符串文字。
-
char文字有什么不能用wchar_t文字做的吗? -
n.m.:将它传递给一个接受 wchar_t 参数的函数? (您可以将 char 扩展为 wchar_t,但这并不能保证它们代表相同的字符,只是相同的整数。)
-
@rici 我的意思是在编译时。
标签: c++ boost c-preprocessor