【问题标题】:Class template instantiation as type template parameter, syntax?类模板实例化为类型模板参数,语法?
【发布时间】:2014-10-22 21:33:42
【问题描述】:
class XY{};

template<typename typeA>
class A
{
(...)
};
template<typename typeB>
class B
{
(...)
};
(...)
     B<class <class XY>A> * attribute; // <- How can I do that without Syntaxerror

尝试这个 gcc 时出现以下错误:

xy.h:19: 错误:模板参数 1 无效

我怎样才能避免这种情况?

【问题讨论】:

  • 正确的语法是B&lt;A&lt;XY&gt;&gt;* attribute,如果你打算用XY实例化A,用A&lt;XY&gt;实例化B

标签: c++ class templates syntax type-parameter


【解决方案1】:

class 关键字仅用于定义模板类,不用于声明对象。为此,您只需要:

B<A<XY> >* attribute;

或者为了清楚起见将其展开:

typedef A<XY> MyA;
typedef B<MyA> MyB;
MyB* attribute;

【讨论】:

  • 值得注意的是B&lt;A&lt;XY&gt;&gt;* attribute;是C++11之前的语法错误。 (对于 C++11 之前的版本,您必须使用 B&lt; A&lt;XY&gt; &gt;* attribute;,否则 &gt;&gt; 会解析为右移运算符。调整了 C++11 语法,以便 &gt;&gt; 可以解析多种方式,具体取决于上下文。)
  • 是的,它认为这是移位运算符。
  • @cdhowie 已修复,我这几天习惯不输入空格了。
【解决方案2】:

你的问题很不清楚,但我认为你在模板模板参数之后。这样:

template <template <class> class U>
class Foo {};

现在Foo 是一个类模板,它接受另一个类模板作为其参数,如下所示:

template <class V>
class Bar {};

Foo<Bar> theFoo;

【讨论】:

  • @MartinErhardt 我编辑了你误导我的问题标题,希望没关系。
  • 有趣的是,这不是我所要求的,而是我稍后实施时需要的。
  • 但是如何在 Foo 中使用 U 呢?: "error: 'U' does not name a type"
  • 您需要实例化U(如U&lt;Something&gt;)。 U 是一个实际的模板,而不是它的任何实例,所以它确实不是一个类型。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多