Initializing a static constant member in a template class

I have a problem initializing a static const member. In the template class, I define the const member and initialize it outside the class.
When I include the .h file, where this class is implemented in several .cpp files, I get the LNK2005 error message (I use VS2010), which says that the constant is already defined .

// List.hpp template <class T> class List { static const double TRIM_THRESHOLD; }; template <class T> const double List<T>::TRIM_THRESHOLD = 0.8; 

I tried putting member initialization in a .cpp file, but then I get a linker error saying that the constant is not defined at all. If the list is not a template, and I put the initialization in the .cpp file, everything is fine.
Is there a solution for this situation? I already have # ifdef / define sentences around the file, and this is definitely not a solution.

+6
c ++ static const visual-c ++ - 2010
source share
1 answer

You should define a constant in the source file, not a header (therefore, it is defined only once), since this is a template that you need to save in the header (and all instances have the same value), you can use a common base class.

 class ListBase { protected: ListBase() {} // use only as base ~ListBase() { } // prevent deletion from outside static const double TRIM_THRESHOLD; }; template <class T> class List : ListBase { }; // in source file double ListBase::TRIM_THRESHOLD = 0.8; 

Another option is to use it as a static function:

  static double trim_threashold() { return 0.8; } 

Edit: If your compiler supports C ++ 11, you create a static constexpr function method, so that it has all the optimization options that directly use the value.

+7
source share

All Articles