简体   繁体   中英

Partial specialization of template class copy constructor

I'm trying to partially specialize the copy constructor of a very basic templated array class.

template<typename D, bool destruct = false> class SimpleArray
{
 SimpleArray(const SimpleArray& other)
 {
  //stuff
 }

 //various other things
}

template<typename D> SimpleArray<D, true>::SimpleArray(const SimpleArray& other)
{
 //different stuff
}

But I get this error:

'SimpleArray<D,destruct>::{ctor}' : unable to match function definition to an existing declaration

However, I've definitely declared the function... I tried changing the parameter in the partial specialization to const SimpleArray<D, true>& other to no avail. VC++ 11 isn't highlighting the partially specialized function name itself, so I'm guessing the issue is an incorrect name somehow.

You cannot specialize a single member function of a certain partial specialization of a class template: if you want to go the specialization way, you have to specialize the whole class.

However, you could decide to go the overload way instead, and differentiate between the case when destruct is true and when it is false through tag dispatching .

For instance, you could define two private member functions called copy_construct , as shown below:

template<typename D, bool destruct = false>
class SimpleArray
{

    // ...

private:

    void copy_construct(const SimpleArray& other, std::true_type)
    {
        // ...
    }

    void copy_construct(const SimpleArray& other, std::false_type)
    {
        // ...
    }
};

And then you could let the copy constructor of your class call the appropriate overload based on the value of the destruct parameter:

template<typename D, bool destruct = false>
class SimpleArray
{

public:

    // ...

    SimpleArray(const SimpleArray& other)
    {
        copy_construct(other, std::integral_constant<bool, destruct>());
    }

    // ...

};

This will invoke the appropriate version of copy_construct() , which will do what ought to be done based on the value of the destruct parameter.

The compiler message is not helpful (and is no better from G++ or Clang) but it's trying to tell you that you can't define a member function of a partial specialization if you haven't already declared the partial specialization.

ie you cannot specialize a single member function of a class template, you have to declare a specialization of the whole class template. The reason is that the constructor is not a template, it's a normal (non-template) member function of a template. To define a partial specialization you have to specialize the whole class template, you can't specialize a non-template.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM