我想定义没有类的模板变量,但 MSVC++ 不接受它,并且根据 C++ 标准,谷歌搜索它似乎是不正确的:
template<CharType> static CharType hexDigits[17];
template<> char hexDigits[17] = "0123456789ABCDEF";
template<> wchar_t hexDigits[17] = L"0123456789ABCDEF";
然后,这些专用变量将在(非专用)模板函数中使用。
所以我被迫这样写:
template<typename CharType> class dummyclass {
static CharType hexDigits[17];
};
template<> char dummyclass<char>::hexDigits[17] = "0123456789ABCDEF";
template<> wchar_t dummyclass<wchar_t>::hexDigits[17] = L"0123456789ABCDEF";
有什么方法可以定义这两个变量而不定义虚拟类吗?
此外,C++ 标准是否有任何充分的理由不允许使用第一段代码?毕竟,类之外的模板函数是允许的。
最佳答案
Also, is there any good reason why the C++ standard does not allow the first piece of code? After all, template functions outside a class are permitted.
请注意:
template<CharType> static CharType hexDigits[17];
template<> char hexDigits[17] = "0123456789ABCDEF";
template<> wchar_t hexDigits[17] = L"0123456789ABCDEF";
有两个不同类型但名称相同的符号:这不可能工作,因此编译器必须开始像对函数和类所做的那样,开始修改/修饰变量的名称。
就干净地实现这一点而言,这对我来说似乎是一个特征......如果您不介意收到链接错误而不是编译错误,您甚至可以跳过特化并仅声明适当的静态成员:
template <typename CharType> struct my_char_traits {
static CharType hex_digits[17];
};
template<> char my_char_traits<char>::hex_digits[17] = "0123456789ABCDEF";
template<> wchar_t my_char_traits<wchar_t>::hex_digits[17] = L"0123456789ABCDEF";
关于c++ - 定义不带类的模板变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12509961/