What is wrong with partial template specialization?

你说的曾经没有我的故事 提交于 2019-12-05 20:37:46

You are trying to partially specialize a method. That is not allowed. You can only partially specialize the whole class. Once you have specialized the class, you can then provide a non-specialized definition of the methods for the partially specialized class.

Here is an example of some code that might do what you want:

template<class T, bool p = true>
class A
{
private:
    T* ptr;
public:
    A();
};

template <class T>
class A<T,true> {
private:
    T* ptr;
public:
    A();
};


template <class T>
class A<T,false> {
private:
    T* ptr;
public:
    A();
};

template<class T>
A<T,true>::A()
{
    ptr = reinterpret_cast<T *>(0xbaadf00d);
}

template<class T>
A<T,false>::A()
{
    ptr = 0;
}

int main()
{
    A<int> obj;
    A<int, false> o;
    return(0);
}

You're welcome to specialize on non-type template parameters, but you can't specialize just one function of a template class. The class is the template, so the class is what you need to specialize. That is, to give a special definition of the constructor, you need to provide a special definition of the entire class.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!