一个类可以包含一个必须是静态的成员模板变量:
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; } };
它必须在类范围之外声明所有静态成员:
以下编译并按预期工作:
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;
这里的语法是什么?