class 模板特殊成员函数显式特化
class template special member function explicit specialization
在 c++ iso 2003/2011 [temp.expl.spec]/4 中这样写
A member function, a member class or a static data member of a class template may be explicitly specialized for a class specialization that is implicitly instantiated; in this case, the definition of the class template shall be in scope at the point of declaration of the explicit specialization for the member of the class template. If such an explicit specialization for the member of a class template names an implicitly-declared special member function (clause 12), the program is ill-formed.
据我所知,允许特化的特殊函数应该在显式特化之前定义。
template <typename T>
class A
{
public:
A()
{ /* some definition */}
};
template <>
A<int>::A()
{ /*explicit specialization def body*/} // this is OK
但是
template <typename T>
class B
{};
template <>
B<int>::B()
{ /*explicit specializationdef body */} // this is forbidden by ISO c++
// and when compiling with VS2013 gives compile error
// cannot define a compiler-generated special member
// function (must be declared in the class first)
为什么会有这样的限制?
这与成员函数的正常工作方式一致。您只能定义您首先声明的函数。例如,这不会编译:
struct B {
};
B::B() {
}
构造函数是隐式声明的,因此不能显式定义。
您引用的段落说这对模板专业化同样有效。
在 c++ iso 2003/2011 [temp.expl.spec]/4 中这样写
A member function, a member class or a static data member of a class template may be explicitly specialized for a class specialization that is implicitly instantiated; in this case, the definition of the class template shall be in scope at the point of declaration of the explicit specialization for the member of the class template. If such an explicit specialization for the member of a class template names an implicitly-declared special member function (clause 12), the program is ill-formed.
据我所知,允许特化的特殊函数应该在显式特化之前定义。
template <typename T>
class A
{
public:
A()
{ /* some definition */}
};
template <>
A<int>::A()
{ /*explicit specialization def body*/} // this is OK
但是
template <typename T>
class B
{};
template <>
B<int>::B()
{ /*explicit specializationdef body */} // this is forbidden by ISO c++
// and when compiling with VS2013 gives compile error
// cannot define a compiler-generated special member
// function (must be declared in the class first)
为什么会有这样的限制?
这与成员函数的正常工作方式一致。您只能定义您首先声明的函数。例如,这不会编译:
struct B {
};
B::B() {
}
构造函数是隐式声明的,因此不能显式定义。
您引用的段落说这对模板专业化同样有效。