热以初始化专用模板代码中的静态 const 成员
Hot to initialize static const member in specialized template code?
我目前无法像我想要的那样设置我的类成员。我的模板化类只专门用于合理的整数类型(无符号和"小")。每个专业化都需要一个相当大的查找表,该表仅取决于类型。所以我认为它绝对应该是静态的(和常量),并且只创建一次。
由于C++没有静态构造函数,我了解到您可以创建一个类,该类在初始化时执行繁重的工作并将其作为静态成员。
我将代码简化为以下基础知识:
// Of this, I only want one instance per type,
// because the table can get big.
template<class T>
struct LookUp
{
static int const SIZE = 1 << (sizeof(T) << 3);
std::vector<T> table;
LookUp()
: table{ SIZE }
{
for (int i = 0; i < SIZE; ++i)
{
// Dummy code
table[i] = i;
}
}
};
// "Normal" template class with common code for all types.
template<class T>
class LbpHelper
{
typedef /*...*/ image;
};
// No functionality for the general case.
template<class T>
class Lbp
{
};
// But for this (among others) we have something.
template<>
class Lbp<uint8_t> : public LbpHelper<uint8_t>
{
typedef uint8_t value_type;
typedef Lbp::image image;
static LookUp<value_type> _lookup; // <-- This is the mean one.
public:
// Stuff...
};
初始化静态成员似乎让很多用户感到困惑,尤其是在模板和专用化方面。我在这里读了很多答案,但没有一个能解决我的问题。
我试过有类似的东西
// The type of the class is the same as the type of the member class.
template<> LookUp<uint8_t> Lbp<uint8_t>::_lookup{};
template<> LookUp<uint16_t> Lbp<uint16_t>::_lookup{};
在标头和/或源文件中。我尝试在尖括号中带或不带class T
(当然在右侧使用T
),完全省略template<>
,仅在源中{}
s - 我不知道还有什么。什么都没用。
视觉C++要么告诉我_lookup
不是成员,要么它不是一个可以专门的实体,或者这个:错误 C2373:"_lookup":重新定义;不同的类型修饰符。
有人可以告诉我在哪里放什么以便编译吗?
只需删除template<>
位,并将静态数据成员的定义放在.cpp文件中:
LookUp<uint8_t> Lbp<uint8_t>::_lookup{};
LookUp<uint16_t> Lbp<uint16_t>::_lookup{};
[现场示例]
。而且,由于_lookup
的类型是一个类,因此您也可以省略{}
;无论如何都会调用它的默认构造函数。如果您使用的版本不支持统一初始化,这可能会让 VC++ 满意。
为什么这是正确的方法:template<>
用于引入明确的专业化。您不是在引入显式专用化 - 您是在定义已定义的显式专用化的数据成员。
这在 C++11 14.7.3/5 中涵盖:
。显式专用类模板的成员包括 定义方式与普通类的成员相同,并且不使用
template<>
语法。一样 在定义显式专用成员类的成员时为 true。
- 初始化类中的静态 const 数组 - C++
- c++ 是否保证标头初始化的静态 const 成员跨编译单元和库共享单个实例?
- 匿名命名空间中的const与静态const
- 内联初始化的静态 const 类成员的初始化顺序保证
- 是否可以按模板类型更改静态 const 类成员的值
- 如何在类中声明静态 const 结构元素
- 与其他静态const成员初始化静态常量成员
- 如何在预处理器 (#if) 中强制转换静态 const 以避免溢出
- 使用模板参数初始化静态 const 成员
- 为什么将FMTFLAG指定两次 - 作为枚举的一部分,而另一个实例为静态const变量
- 将整数值分配为variadic模板列表到静态const std ::数组成员
- 静态const数据成员在另一个文件中定义
- 初始化在 C++ 中自定义类的构造函数中没有参数的静态 const 类成员
- 将静态 const 成员重新声明为 constexpr 是否会自动使其符合内联条件
- constexpr vs.静态const:哪个更喜欢
- 静态const颜色无法与Allegro5完全合作
- 模板类中的不可复制静态 const 成员类
- 编组静态const char*从C 到C#
- 枚举和静态const成员变量在模板特征类中的用法
- 在性能和内存使用方面,“静态const”,“ #define”和“枚举”之间的差异