Search code examples
c++templatesspecialization

explicit specialization in template class error


my problem is the following, I have a template object, and in this object a method also template, for which I want to make a specialization, only the compiler always returns an error: "a declaration of model containing a list of model parameters can not be followed by an explicit specialization declaration. I would like to understand in this case if how to specialize the method, here is the code:

 template<typename T>class Foo
{
    public:
        template<typename T2> Foo<T2> cast(void);

};



template<typename T> template<typename T2> Foo<T2>   Foo<T>::cast(void)
{
    Foo<T2> tmp;

    std::cout << "1" << std::endl;

    return tmp;
}

template<typename T> template<> Foo< int >  Foo<T>::cast< int >(void)
{
    Foo<int> tmp;
    
    std::cout << "2" << std::endl;

    return tmp;
}

int main()
{
 Foo<double> bar();
 bar.cast<int>();
}

Solution

  • The problem is that we can't fully specialize the member function template without also fully specializing the class template also. This means that the correct syntax would be as shown below:

    template<typename T> struct CompressVector
    {
        template<typename T2> CompressVector<T2> cast();
    };
    template<typename T> template<typename T2> CompressVector<T2>   CompressVector<T>::cast()
    {
        CompressVector<T2> tmp;
    
        //other code here
        return tmp;
    }
    //vvvvvvvvvv-vvvvvvvvv-------------------------------------vvv------------>made changes here
    template<> template< > CompressVector<int>  CompressVector<int>::cast< int >(void)
    {
        CompressVector<int> tmp;
        //other code here
        
        return tmp;
    }
    

    Working demo