0

When I have a class that can be boiled down to something like this:

// test.hpp
class Test{
public:
  template<typename T> static T value;
};

template<typename T> Test::value = {};

I can use this class when I only look up an instantiated value in one .cpp file. But when I try to use this in multiple .cpp files I get an already defined linker error.

//somefile1.cpp
include "test.hpp"
void fn(){
  int i = Test::value<int>;
}

// somefile2.cpp
include "test.hpp"
void otherfn(){
  // public static int value already defined in somefile1.obj
  int j = Test::value<int>;
}

Putting template<typename T> Test::value = {} into its own .cpp file gives an unresolved external error for all uses. What's the problem?

SergeyA
  • 61,605
  • 5
  • 78
  • 137
val
  • 729
  • 6
  • 19
  • Can't reproduce. (after fixing syntax for definition of template variable). What compiler are you using? – SergeyA Nov 15 '16 at 15:33
  • I am using VS2015, I guess its uses its default compiler. – val Nov 15 '16 at 15:34
  • Works perfectly fine in gcc, and creates weak symbol as expected. I suggest you actually fix your example to be correct syntax. – SergeyA Nov 15 '16 at 15:35

0 Answers0