shane shane - 23 days ago 13
C++ Question

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

Answer

Add

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

after class definition.

Demo

Comments