c++ template partial specialization member function [duplicate]

一曲冷凌霜 提交于 2019-11-26 16:32:29

You cannot partially specialize only a single member function, you must partially specialize the whole class. Hence you'll need something like:

template <typename T>
class Object<T, 0>
{
private:
    T m_t;
    Object();
public:
    Object(T t): m_t(t) {}
    T Get() { return m_t; } 
    Object& Deform()
    {
        std::cout << "Spec\n";
        m_t = -1;
        return *this;
    }
};

14.5.5.3.1. The template parameter list of a member of a class template partial specialization shall match the template parameter list of the class template partial specialization. The template argument list of a member of a class template partial specialization shall match the template argument list of the class template partial specialization.

In other words: no partially specialized member without partially specialized class.

Unfortunately, you can't partially specialize member function of a template class. You may either partially specialize the whole class or use inheritance. You may also use both:

template <typename T, int nValue>
class Object {
protected:
    T m_t;
public:
    Object() = delete;
    Object(T t): m_t(t) {}
    T Get() { return m_t; }
    Object& Deform() {
        m_t *= nValue; 
        return *this;
    }
};

template <typename T>
class Object<T,0> : public Object<T,1> {
public:
    using Object<T,1>::Object;

    Object& Deform() {
        this->m_t = -1;
        return *this;
    }
};
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!