【问题标题】:class template special member function explicit specialization类模板特殊成员函数显式特化
【发布时间】:2015-03-04 14:22:40
【问题描述】:

在 c++ iso 2003/2011 [temp.expl.spec]/4 中写到

类模板的成员函数、成员类或静态数据成员可以显式特化为隐式实例化的类特化;在这种情况下,类模板的定义应在类模板成员的显式特化声明点的范围内。如果类模板成员的这种显式特化命名了一个隐式声明的特殊成员函数(第 12 条),则程序是非良构的。

因此,据我了解,应在显式特化之前定义允许特化的特殊功能。

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)

有这些限制的原因是什么?

【问题讨论】:

  • 特殊成员函数不需要在显式特化之前定义,它们只需要显式声明。 (这类似于不能定义非模板类的隐式声明的特殊成员函数的限制。)

标签: c++ templates member-functions explicit-specialization


【解决方案1】:

这与成员函数定义的正常工作方式是一致的。您只能定义您首先声明的函数。例如这不会编译:

struct B {
};

B::B() {
}

构造函数是隐式声明的,所以不能显式定义。

您引用的段落说这对于模板专业化同样有效。

【讨论】:

    猜你喜欢
    • 2011-07-27
    • 2012-04-03
    • 1970-01-01
    • 2012-05-09
    • 1970-01-01
    • 2011-08-22
    • 2013-09-24
    相关资源
    最近更新 更多