热以初始化专用模板代码中的静态 const 成员

Hot to initialize static const member in specialized template code?

本文关键字:静态 const 成员 代码 初始化 专用      更新时间:2023-10-16

我目前无法像我想要的那样设置我的类成员。我的模板化类只专门用于合理的整数类型(无符号和"小")。每个专业化都需要一个相当大的查找表,该表仅取决于类型。所以我认为它绝对应该是静态的(和常量),并且只创建一次。

由于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。