【问题标题】:Container passed as template argument to class-template容器作为模板参数传递给类模板
【发布时间】:2011-12-22 08:16:31
【问题描述】:

我正在尝试创建一个简单的模板类,其中我创建模板类的一个对象,提供一个容器作为模板类型,根据我对模板的理解,这应该没问题,应该像 int 或 char 一样处理,但它总是给我一个错误说:

"template argument 1 is invalid"

这是我遇到此错误的行:

templateTest<(std::list<int>)> testingTheTemplate;

这是模板类的骨架

template <class testType> class templateTest 
{
   /* use some iterators and print test data here */
};

我在这里错过了什么?

【问题讨论】:

  • 那只会创建一个模板类型为“int”的模板,这不是我想要做的。
  • 你忘了放吗? (冒号)在类定义之后?我的意思是在你的第二个代码 sn-p 的末尾?

标签: c++ templates


【解决方案1】:

您忘记了类定义后的分号:

template <class testType> class templateTest 
{

}; // <- semicolon

另外,声明你的实例如下:

templateTest<std::list<int> > testingTheTemplate;
                       // ^^^ required space (C++03)

没有括号,注意中间的空格。

在 C++11 之前,&lt;&lt;&gt;&gt; 被视为运算符。在这种情况下,您必须将它们分开。

【讨论】:

  • 好的,这是新的,我的印象是空格在 C++ 中从来没有任何区别(除非在标记中使用会导致 foobar 的东西)谢谢你的帮助!
  • 在这种情况下他们会这样做。 >> 和
  • Nitpick:这不是专门化,而是实例化。
  • @BjörnPollex 从为模板指定类型的角度来看,它是一种专业化,但是创建了该专业化类的实例,对吗?我们仍然将场景称为专业化吗?
  • 这也是我的推理......但专业化不是一个不同的声明,其实现以特定方式运行吗?
【解决方案2】:

在 C++03 中应该是
templateTest&lt;std::list&lt;int&gt; &gt; testingTheTemplate;
或 C++11 中的 templateTest&lt;std::list&lt;int&gt;&gt; testingTheTemplate;

【讨论】:

  • templateTest<:list>> 不起作用,这是我最初给出的,但似乎 get from '>>' 运算符具有更高的优先级。
  • @angryInsomniac:这就是为什么他同时提供了旧的 c++03 版本(存在该问题)和新的 C++11 版本(不支持但并非所有人都支持)编译器或需要特殊的编译器标志)
  • @angryInsomniac 你的编译器不支持当前的 C++ 标准 (C++11)
  • 它确实适用于遵循 C++11 标准的较新编译器。也许您的编译器可以采用 -c++0x 或 -c++11 选项?
  • @Abyx 我不确定,我在工作中使用 MAC 进行一些学习活动,OSX 和 X-code 并不是我真正喜欢的,我会在家里检查我的 Windows 机器,然后看看它的工作原理。
猜你喜欢
  • 2011-09-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-08
  • 1970-01-01
相关资源
最近更新 更多