gpt4 book ai didi

c++ - 确保构造类的静态成员

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

考虑以下代码

#include <iostream>
using namespace std;

struct Printer{
Printer(){
std::cout << "Created\n";
}
};

template<class Derived>
struct InitPrinter{
static Printer p;
};

template<class Derived>
Printer InitPrinter<Derived>::p;


struct MyClass:InitPrinter<MyClass>{
MyClass(){}

};

// Uncomment line below to print out created
//auto& p = MyClass::p;

int main() {
return 0;
}

我预计这会打印出“Created”,然而,它没有打印出任何东西(使用 MSVC 和 ideone gcc c++11 测试)。这是编译器实现问题,还是标准支持这种行为?如果注释掉的行未被注释,则它会按预期打印出来。有什么方法可以实例化 static Printer p 而无需更改 MyClass 或像 auto& p = MyClass::p 这样的额外语句?

我对此感兴趣的原因是我希望创建一个模板化的基类,当它从中派生时,它将在启动时运行一些代码。

最佳答案

适当的引用是 [temp.inst]/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.

强调我的。


还有[temp.inst]/1

The implicit instantiation of a class template specialization causes the implicit instantiation of the declarations, but not of the definitions or default arguments, of the class member functions, member classes, scoped member enumerations, static data members and member templates [...]

和 [temp.inst]/10

An implementation shall not implicitly instantiate a function template, [...] or a static data member of a class template that does not require instantiation.

关于c++ - 确保构造类的静态成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19964575/

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