c++ - 定义不带类的模板变量

标签 c++ templates

我想定义没有类的模板变量,但 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/

相关文章:

c++ - 从基类覆盖虚方法

c++ - 如何在没有任何内存泄漏的情况下创建和编辑全局 PCHAR

c++ - enable_if 使用 constexpr bool 测试不起作用

c++ - 如何在编译时创建具有 string_views 序列的 constexpr 数组?

C++ KOALA 图形库 - 了解访问数据结构的语法

从头文件内部引用类的实现时,c++模板类错误

c++ - 在此上下文中的完美转发和 std::move 行为

c++ - 检查使用 SDL2 播放的音乐

C++:基类调用自己的虚函数——一种反模式?

c++ - 具有派生类的模板化数据类型