Template partial specialization with multiple template argument error

后端 未结 2 2011
深忆病人
深忆病人 2020-12-30 15:33

When I use template partial specialization on a class with one template argument, I can specialize a method like this:

#include 

template<         


        
2条回答
  •  旧时难觅i
    2020-12-30 16:04


    Editing since I cannot post comments yet (50 rep heh)...

    Philippe, in response to your comment this morning, according to the standard you cannot partially specialize a member of a class template, you can only fully specialize them (whether it be a class template, a function, a function template, etc...). In your first example, you are fully specializing the member function foo. In your second example, you are partially specializing, reason why it will not compile. You can fully specialize it this way:

    template< >
    inline int Test< int, 2 >::foo()
    {...}
    

    Although Konrad's code snipet is perfectly legal, I'm not sure the reason provided as to why Philippe's code doesn't compile is correct. (Although, as Konrad mentionned, you cannot partially specialize a function template).

    The issue at hand, in Philippe's code, is that we are declaring a class template and not a function template. Hence, a partial class template specialization declaration is needed for the partial specialization definition to be legal.

    #include 
    
    template< typename T, std::size_t Dim >
    class Test
    {
    public:
        int foo();
    };
    
    template < typename T >
    class Test < T, 1 >
    {
    public:
        int foo();
    };
    
    
    template< typename T, std::size_t Dim >
    inline int Test< T, Dim >::foo()
    {
        return 0;
    }
    
    template< typename T >
    inline int Test< T, 1 >::foo()
    {
        return 1;
    }
    
    int main()
    {
        Test< double, 2 > wTest2;
        Test< int, 1 > wTest1;
        wTest2.foo();
        wTest1.foo();
        return 0;
    }
    

提交回复
热议问题