6

クラスには、静的でなければならないメンバー テンプレート変数を含めることができます。

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...

しかし、次の動作しないコードのような変数を特殊化する方法 (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;

ここで正しい構文は何ですか?

4

1 に答える 1