template specialization for static member functions; howto?

后端 未结 5 770
情歌与酒
情歌与酒 2021-02-05 19:03

I am trying to implement a template function with handles void differently using template specialization.

The following code gives me an \"Explicit specialization in non

5条回答
  •  北海茫月
    2021-02-05 19:40

    When you specialize a templated method, you must do so outside of the class brackets:

    template  struct Test {}; // to simulate type dependency
    
    struct X // class declaration: only generic
    {
       template 
       static void f( Test );
    };
    
    // template definition:
    template 
    void X::f( Test ) {
       std::cout << "generic" << std::endl;
    }
    template <>
    inline void X::f( Test ) {
       std::cout << "specific" << std::endl;
    }
    
    int main()
    {
       Test ti;
       Test tv;
       X::f( ti ); // prints 'generic'
       X::f( tv ); // prints 'specific'
    }
    

    When you take it outside of the class, you must remove the 'static' keyword. Static keyword outside of the class has a specific meaning different from what you probably want.

    template  struct Test {}; // to simulate type dependency
    
    template 
    void f( Test ) {
       std::cout << "generic" << std::endl;
    }
    template <>
    void f( Test ) {
       std::cout << "specific" << std::endl;
    }
    
    int main()
    {
       Test ti;
       Test tv;
       f( ti ); // prints 'generic'
       f( tv ); // prints 'specific'
    }
    

提交回复
热议问题