【发布时间】:2020-11-09 06:11:41
【问题描述】:
这是我的 simplestring 类——一个模板类,它应该同时处理 char 字符串和 wchar_t 字符串。我想为 char 字符串和 wchar_t 字符串定义一个 default_separator:
When _Thar is char, default_separator is "\n" and when _Thar is wchar_t, default_separator is L"\n"
我将 MACRO DEFAULT_SEPARATOR 定义为“\n”,并且我想为指定的成员 simplestring::default_separator 和 simplestring
template<typename _TChar>
struct simplestring
{
#define DEFAULT_SEPARATOR "\n"
static const _TChar* default_separator;
void show_tstring()
{
throw "no implement";
}
};
template<>
const char* simplestring<char>::default_separator = DEFAULT_SEPARATOR;
template<>
const wchar_t* simplestring<wchar_t>::default_separator = L##DEFAULT_SEPARATOR; //doesn't compile
void simplestring<char>::show_tstring()
{
cout << "char string\n";
cout << default_separator << endl;
}
void simplestring<wchar_t>::show_tstring()
{
cout << "wchar_t string\n";
wcout << default_separator << endl;
}
static void test()
{
simplestring<char> s;
s.show_tstring();
simplestring<int> s2;
s2.show_tstring();
}
关键行L##DEFAULT_SEPARATOR 编译时出错
Error C2014 preprocessor command must start as first nonwhite space ForTest
【问题讨论】:
-
##只能在类似函数的#define指令中工作,并且只能使用此类指令的参数,因此您需要为##创建一个类似函数的宏。事实上,你需要 two 层这样的宏,参见例如stackoverflow.com/questions/8231966/…