Static const member initialization in templated class

Gra*_*Lup 7 c++ static const visual-c++-2010

I have a problem regarding 'static const' member initialization. In a templated class I define a const member and initialize it outside the class.
When I include the .h file where this class is implemented in multiple .cpp files, I get an LNK2005 error (I'm using VS2010) that says 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;
Run Code Online (Sandbox Code Playgroud)

我尝试将成员初始化放在.cpp文件中,但后来我得到一个链接器错误,说根本没有定义常量.如果列表没有模板化,我将初始化放在.cpp文件中,一切都很好.
这种情况有什么解决方案吗?我已经在文件周围有#ifdef/define子句,这绝对不是解决方案.

Mot*_*tti 8

您应该在源文件中定义常量而不是标题(因此它只定义一次),因为这是您需要保留在标题中的模板(并且所有实例具有相同的值),您可以使用公共基类.

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;
Run Code Online (Sandbox Code Playgroud)

另一个选择是将它作为静态函数:

    static double trim_threashold() { return 0.8; }
Run Code Online (Sandbox Code Playgroud)

编辑:如果您的编译器支持C++ 11,那么您可以使您的static方法成为一个constexpr函数,以便它具有直接使用该值的所有优化机会.