成员模板变量特化

member template variable specializing

A class 可以包含一个必须是静态的成员模板变量:

class B
{   
    public:
        template <typename X>
            static X var;

        B() { std::cout << "Create B " << __PRETTY_FUNCTION__ << std::endl; }

        template <typename T>
        void Print() { std::cout << "Value is " << var<T> << std::endl; }
};

必须在 class 范围外声明所有静态成员:

以下编译并按预期工作:

 template<typename T> T B::var=9; // makes only sense for int,float,double...

但是如何像以下非工作代码那样专门化这样的 var(gcc 6.1 的错误消息):

template <> double B::var<double>=1.123; 

失败:

main.cpp:49:23: error: parse error in template argument list
 template <> double B::var<double>= 1.123;
                       ^~~~~~~~~~~~~~~~~~
main.cpp:49:23: error: template argument 1 is invalid
main.cpp:49:23: error: template-id 'var<<expression error> >' for 'B::var' does not match any template declaration
main.cpp:38:22: note: candidate is: template<class X> T B::var<T>
             static X var;

template <> double B::var=1.123;

失败

   template <> double B::var=1.123;
                       ^~~
main.cpp:38:22: note: does not match member template declaration here
             static X var;

此处正确的语法是什么?

我想你应该添加一个 space

template <> double B::var<double> = 1.123;
                                 ^ here

否则(如果我没记错的话)>=1.123 与 "equal or greather than 1.123"

混淆了