gpt4 book ai didi

c++ - 如果不使用静态成员,是否在模板类中初始化静态成员变量?

转载 作者:太空狗 更新时间:2023-10-29 21:01:10 24 4
gpt4 key购买 nike

如果不使用静态成员,是否在模板类中初始化静态成员变量?我用它来注册类型。

template<class T>
class A
{
static bool d;
};

template<class T> bool A<T>::d = [](){regist<A<T>>(); return true;}();

int main()
{
A<int> a;
return 0;
}

我找到了测试它的方法。它打印 1 而不是 2。regist() 未被调用,静态成员未初始化。我的测试是在 VC110 编译器上进行的。我也测试了它online

#include <iostream>
using namespace std;

int i = 1;

template<class T>
void regist()
{
++i;
}

template<class T>
class A
{
static bool d;
};

template<class T> bool A<T>::d = [](){regist<A<T>>(); return true;}();

int main()
{
A<int> a;
cout << i << endl;
return 0;
}

最佳答案

C++ draft standard的相关栏目属于 14 Templates,即 14.7.1 Implicit instantiation 段落 2 说(强调我的):

Unless a member of a class template or a member template has been explicitly instantiated or explicitly specialized, the specialization of the member is implicitly instantiated when the specialization is referenced in a context that requires the member definition to exist; in particular, the initialization (and any associated side-effects) of a static data member does not occur unless the static data member is itself used in a way that requires the definition of the static data member to exist.

我们还可以看到 8 段说:

The implicit instantiation of a class template does not cause any static data members of that class to be implicitly instantiated.

但是,如果您向第二种情况添加一个显式实例化,您将看到 2 作为结果:

template<> bool A<int>::d = [](){regist<A<int>>(); return true;}();

关于c++ - 如果不使用静态成员,是否在模板类中初始化静态成员变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19341360/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com