部分模板专业化有什么问题?

Ser*_*rge 3 c++ templates partial-specialization

我正在编写一个带有一个类型参数和一个布尔值的模板类,这里是代码:

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


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

int main()
{
    A<int> obj;
    A<int, false> o;
    return(0);
}
Run Code Online (Sandbox Code Playgroud)

我收到这些编译错误:

Error   1   error C3860: template argument list following class template name must list parameters in the order used in template parameter list tst.cpp 15
Error   2   error C2976: 'A<T,p>' : too few template arguments  tst.cpp 15
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?或者由于某种原因禁止部分专门化非类型参数?

同时,如果我在if语句中使用boolean参数,我收到此警告:

Warning 1   warning C4127: conditional expression is constant
Run Code Online (Sandbox Code Playgroud)

所以我应该为这类事做专业化......

任何帮助将非常感谢!:)

提前致谢!!!!

Vau*_*ato 7

您正在尝试部分专门化方法.这是不允许的.你只能部分专门化整个班级.一旦您对该类进行了专门化,就可以为部分专用的类提供非专业的方法定义.

以下是一些可能符合您要求的代码示例:

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);
}
Run Code Online (Sandbox Code Playgroud)


Rob*_*edy 6

您可以专注于非类型模板参数,但不能专门使用模板类的一个函数.本是模板,因此是你需要专注的东西.也就是说,要给出构造函数的特殊定义,您需要提供整个类的特殊定义.