shane
shane

Reputation: 1863

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? 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

Upvotes: 1

Views: 49

Answers (1)

Jarod42
Jarod42

Reputation: 217990

Add

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

after class definition.

Demo

Upvotes: 2

Related Questions