shane shane - 11 months ago 66
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
default constructed for each template instantiation of
? 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 Source


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

after class definition.