【问题标题】:Partial specialization of member function [duplicate]成员函数的部分特化[重复]
【发布时间】:2012-09-09 01:10:09
【问题描述】:

可能重复:
“invalid use of incomplete type” error with partial template specialization

为什么我可以这样做:

template <typename T>
struct A
{
    void foo(int);
};

template <>
void A<int>::foo(int)
{
}

但不是这个:

template <typename> struct C {};

template <typename T>
struct A
{
    void foo(int);
};

template <typename T>
void A<C<T> >::foo(int)
{
}

对于第二种情况,GCC 给出以下错误:

test.cpp:10:23: error: invalid use of incomplete type 'struct A<C<T> >'
test.cpp:4:8: error: declaration of 'struct A<C<T> >'

编辑

在解释为什么不允许第二个示例时,还请考虑使成员函数也成为模板对哪个示例有效和哪个无效没有影响。也就是说,这仍然有效:

template <typename T>
struct A
{
    template <typename U>
    void foo(U);
};

template <>
template <typename U>
void A<int>::foo(U)
{
}

但事实并非如此:

template <typename> struct C {};

template <typename T>
struct A
{
    template <typename U>
    void foo(U);
};

template <typename T>
template <typename U>
void A<C<T> >::foo(U)
{
}

所以原因不能是函数模板只能完全特化,因为第三个示例不是完全特化(模板参数U 仍然存在),但它仍然有效。

【问题讨论】:

  • @Mankarse 这似乎是一个不同的问题。

标签: c++ templates template-specialization partial-specialization


【解决方案1】:

函数模板只能完全特化,不能部分特化。

您使用的是类模板的成员函数本身就是函数模板这一事实,因此该规则仍然适用。


至于您的编辑:从 14.7.3/1 开始,以下内容可以明确(即完全)专门化:

以下任何一项的明确特化:

——函数模板

——类模板

类模板的成员函数

——类模板的静态数据成员

——类模板的成员类

——类模板的成员枚举

——类或类模板的成员类模板

——类或类模板的成员函数模板

可以通过template&lt;&gt;;引入的声明来声明

我已经强调了适用于您的案例的两个陈述。在没有任何其他明确规定的情况下,这些实体不能被部分专门化。

【讨论】:

  • 我不确定我是否认同这个解释。假设我将成员函数本身设为模板,模板参数为U。然后我仍然可以定义A&lt;int&gt;::foo(U),但不能定义A&lt;C&lt;T&gt;&gt;::foo(U)。然而,第一个很难被认为是一个完整的专业化,因为它有一个模板参数 (U)。
  • @HighCommander4:我说的是“成员函数”,而不是“成员模板”。如果您更改问题,我会更改答案:-)
  • @HighCommander4:好的。确保您了解A&lt;T&gt;::foo 在其整体 中被视为函数模板。对于任何其他类型的类成员,无论是值、类型还是模板,都没有类似的概念。 只有成员功能是特殊的。
  • 再看一遍,仍然没有意义。你说“成员模板没有这种特殊待遇,所以不能单独替换”,但是在我的第三个例子中,我不是单独替换成员模板功能吗?
  • @HighCommander4:你说得对。我现在查了一下,看看编辑。
猜你喜欢
  • 2013-02-28
  • 1970-01-01
  • 1970-01-01
  • 2012-12-15
  • 2012-04-11
  • 1970-01-01
  • 1970-01-01
  • 2022-01-11
相关资源
最近更新 更多