【问题标题】:C++ Partial Template Specialization:Undeclared identifier errorC++ 部分模板专业化:未声明的标识符错误
【发布时间】:2019-03-05 20:56:35
【问题描述】:

编写此代码的目的是更好地理解部分模板专业化。我正在尝试使用三种不同的布尔值对 Vector 类进行部分专业化。

我有一个枚举(对于我的布尔值)定义为:

enum MY_BOOL
{
   YES,
   NO,
   MAYBE
};

对于我的主要模板类,我有

template<class A,MY_BOOL,class B>
class Vector{};

我拥有的部分专业化课程是

template<MY_BOOL b>
class Vector<A,YES,B>{};

编译器抱怨AB 是未声明的标识符,并且部分专用Vector 的参数太少。不抱怨'YES' 这让我很困惑,因为AB 已经在主模板类中定义了。我不需要将它们放回部分专门化类的参数列表中,因为该参数列表的重点是只包含我想要专门化的变量。

【问题讨论】:

  • AB 是您的部分专业化的实际类型吗?请添加minimal reproducible example
  • @NathanOliver 它们不像 int 或 char 但目的是在不同的模板结构中传递。关键字类应该处理这个吗?
  • 你不能做这样的专业化。 AB 仅适用于 template&lt;class A,MY_BOOL,class B&gt; class Vector{};。在template&lt;MY_BOOL b&gt; class Vector&lt;A,YES,B&gt;{}; 中它们不存在。
  • @NathanOliver 所以换句话说,我必须在我的模板参数列表中包含 A 和 B 以用于部分专用模板类?
  • 是的,但它不会是部分专业化。你为什么要在这里实现?

标签: c++ templates partial-specialization


【解决方案1】:

template<MY_BOOL b>
class Vector<A,YES,B>{};

由于未指定 AB,您会收到编译器错误。它不会使用主模板中的AB,它只会使用特化中定义的类型/值。

由于您想要对每个枚举值进行专门化,您可以这样做

template<class A,MY_BOOL,class B>
class Vector {};

template<class A, class B>
class Vector<A, YES, B>{ /* YES stuff */ };

template<class A, class B>
class Vector<A, NO, B>{ /* NO stuff */ };

template<class A, class B>
class Vector<A, MAYBE, B>{ /* MAYBE stuff */ };

现在您对每个枚举都有了专门化。

【讨论】:

  • @BrogrammerDude 它工作正常here
  • 如果我要实现成员函数,除了在单独的 .cpp 文件中包含成员函数上方的模板参数列表之外,我还需要做任何花哨的事情吗?
  • @BrogrammerDude You should not put the template in a cpp file。对于所有的外线成员定义,您需要template&lt;class A, class B&gt; return_type Vector&lt;A, MAYBE, B&gt;::function_name(parameters) {}
【解决方案2】:

YES 的部分特化如下所示:

template<class A, class B>
class Vector<A, YES, B>
{ ... };

偏特化的意思是,你提供与基础模板不同的模板参数,自己填写基础模板缺失的模板参数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    • 2021-08-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多