模板基类中的静态变量

Static variable inside a template base class

本文关键字:静态 变量 基类      更新时间:2023-10-16

这不打印任何内容:

#include <iostream>
template <typename Derived>
struct A
{
static int test()
{
std::cout << "test" << std::endl;
return 0;
}
static inline int a = test();
};
struct B : public A<B>
{
};
int main(int argc, char** argv)
{
return EXIT_SUCCESS;
}

但这确实:

#include <iostream>
template <typename Derived>
struct A
{
};
struct B : public A<B>
{
static int test()
{
std::cout << "test" << std::endl;
return 0;
}
static inline int a = test();
};
int main(int argc, char** argv)
{
return EXIT_SUCCESS;
}

还有这个:

#include <iostream>
struct A
{
static int test()
{
std::cout << "test" << std::endl;
return 0;
}
static inline int a = test();
};
struct B : public A
{
};
int main(int argc, char** argv)
{
return EXIT_SUCCESS;
}

不知道为什么或解决方法。我需要"派生"类型将其注册到静态表中。

第一个代码段不打印任何内容的原因是静态变量未实例化。您必须使用该变量才能实例化它。

[温度]/2

类模板专用化的隐式实例化导致 声明的隐式实例化,但不是类的定义、默认参数或 noexcept-说明符 成员函数、成员类、作用域成员枚举、静态 数据成员、成员模板和好友

作为解决方法,您可以只使用该变量:

int main(int argc, char** argv)
{
(void) B::a;
return EXIT_SUCCESS;
}

由于A是一个模板类,因此除非使用静态内联函数/变量,否则它们实际上不会从模板实例化。因此,您可以执行以下操作:

#include <iostream>
template <typename Derived>
struct A
{
static int test()
{
std::cout << "test" << std::endl;
return 0;
}
static inline int a = test();
};
struct B : public A<B>
{
static inline int b = a;
};
int main(int argc, char** argv)
{
return 0;
}

演示

(自动(解决方案(如此处所述(是创建一个使用注册变量的构造函数。此外,仅当构造对象时,才会初始化变量。

#include <iostream>
template <typename Derived>
struct A
{
A()
{
a = 0;
}
static int test()
{
std::cout << "test" << std::endl;
return 0;
}
static inline int a = test();
};
struct B : public A<B>
{
};
int main(int argc, char** argv)
{
B b;
return EXIT_SUCCESS;
}

"a = 0"是为了避免未使用变量的警告。开销应最小。

演示