简体   繁体   English

如何默认初始化静态类模板变量

[英]How can I default initialize static class template variables

In the following code 在下面的代码中

#include <iostream>
#include <string>
#include <type_traits>

template<class T, typename =  std::enable_if<std::is_default_constructible<T>::value>>
struct E {
    static T var;   
};

int main() {
    std::cout << E<std::string>::var << std::endl;
}

How can I have E<T>::var default constructed for each template instantiation of E ? 如何为E每个模板实例构造E<T>::var默认值? Currently I receiev linker error 目前我收到链接器错误

/home/tE1MjB/ccEXSZtn.o: In function `main':
prog.cpp:(.text.startup+0x12): undefined reference to `E<std::string, std::enable_if<true, void> >::var'
collect2: error: ld returned 1 exit status

Add

template<class T, typename T2> T E<T, T2>::var{};

after class definition. 在类定义之后。

Demo 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何声明/定义/初始化模板类的静态成员变量为类的静态成员变量? - How can I Declare/define/initialize a static member variable of template classes as static member variables of a class? 如何在模板类中初始化此静态类变量? - How do I initialize this static class variable in my template class? 我可以统一初始化模板类的静态const成员吗? - Can I uniformly initialize a static const member of template class? 如何在标头中初始化类变量? - How can I initialize class variables in a header? 如何初始化具有特征类型的类模板的静态数据成员? - How can I initialize a static data member of a class template with type traits? 如何在默认构造函数中初始化模板类型的变量 - How can I initialize a variable of template type in a default constructor 如何初始化静态类的pimple习语的d(指针)? - How can I initialize the d (pointer) of the pimple idiom of an static class? 如何在类中初始化静态const对象并使用它? - How can I initialize a static const object in a class and use it? "如何在没有默认构造函数的情况下初始化类的 std::array?" - How can I initialize an std::array of a class without a default constructor? 我可以初始化静态 const 类成员吗? - Can I initialize static const class member?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM