C++ 确保构造类的静态成员

C++ 确保构造类的静态成员,c++,c++11,static,C++,C++11,Static,考虑以下代码 #include <iostream> using namespace std; struct Printer{ Printer(){ std::cout << "Created\n"; } }; template<class Derived> struct InitPrinter{ static Printer p; }; template<class Derived> Printer

考虑以下代码

#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;
}
#包括
使用名称空间std;
结构打印机{
打印机(){

标准::cout合适的报价是[temp.inst]/2

除非类模板或成员模板的成员已显式实例化或显式 专门化,成员的专门化在引用专门化时隐式实例化 在需要成员定义存在的上下文中;尤其是初始化(以及任何关联的 静态数据成员的副作用)不会发生,除非静态数据成员本身以某种方式使用 这需要存在静态数据成员的定义。

我的


还有[temp.inst]/1

类模板专门化的隐式实例化会导致隐式 实例化类成员函数、成员类、作用域成员枚举、静态数据成员和成员模板的声明,但不实例化定义或默认参数[…]

和[温度仪表]/10

实现不应隐式实例化函数模板[…]或不需要实例化的类模板的静态数据成员


相关:[temp.inst]/10“实现不应隐式实例化函数模板,[…]或不需要实例化的类模板的静态数据成员。”并且从类模板专门化派生不需要实例化(定义)它的静态数据成员。@DyP为什么这不是答案?@AlexanderB因为它很短,而我很懒?:PI通过将auto&p更改为Printer p使其工作,但我想这不是您想要的:p