【问题标题】:GCC template errorsGCC 模板错误
【发布时间】:2012-04-09 16:41:32
【问题描述】:

我正在尝试将 C++ 项目移植到 iOS。它在 Linux 和 Windows 以及 MSVC 上的 QtCreator 中编译得很好。 现在在 Xcode/GCC 上,使用某个模板类我得到以下错误:“错误:模板参数列表太少”。

导致此错误的代码如下所示:

template <typename TA, typename TB, int Type>
class MyClassImpl
{
public:
   MyClassImpl();
   virtual int GetType() const
   {
       return type;
   }
};    

typedef MyClassImpl<float, int, 12> MyFloatIntClass;

MyFloatIntClass::MyFloatIntClass()
{
...
}

int MyFloatIntClass::GetType() const
{
   return 22;
}

我猜想关于 typedef 语法的某些东西是非法的,而 GCC 的标准更加严格。 谁能告诉我到底是什么问题以及如何解决?

【问题讨论】:

  • 如果这是您真实代码的复制/粘贴,那么您在 typedef 之前的课程之后缺少一个 ;

标签: c++ templates gcc


【解决方案1】:

当您定义各个类的方法的完整特化时,您仍然需要在定义前加上 template &lt;&gt;,这是您缺少的“模板参数列表”。此外,构造函数必须按类命名,因此MyFloatIntClass::MyFloatIntClass() 是非法的(因为MyFloatIntClass 只是一个别名,而不是类名)。以下对我来说编译得很好(g++ 4.5.3):

template <typename TA, typename TB, int Type>
class MyClassImpl
{
public:
   MyClassImpl();
   virtual int GetType() const
   {
       return Type;
   }
};    

typedef MyClassImpl<float, int, 12> MyFloatIntClass;

template <>
MyFloatIntClass::MyClassImpl()
{
}

template <>
int MyFloatIntClass::GetType() const
{
   return 22;
}

【讨论】:

  • 这样的作品,谢谢!但是:并非适用于所有情况。我还有一个复制构造函数和一个 operator=,但我不知道如何处理它们。我将更新示例源代码供您查看。忍受我。
  • 谢谢,就是这样。这个模板类我还有一些其他问题,但我想我会为他们打开另一个问题。非常感谢!
【解决方案2】:

这只是一个猜测,但是否需要添加模板?

既然是模板特化,我相信还是需要模板的。

例如

template<>
MyFloatIntClass::MyClassImpl() {}

template<>
int MyFloatIntClass::GetType() const {
    return 22;
}

编辑:根据 modelnine 的回答——原来它需要 ctor 的无类型定义名称。

EDIT2:以下代码对我来说很好:

template <typename TA, typename TB, int Type>
class MyClassImpl
{
public:
   MyClassImpl();
   MyClassImpl(const MyClassImpl<TA, TB, Type>&);
   virtual int GetType() const
   {
       return Type;
   }
   const MyClassImpl<TA, TB, Type>& operator=(const MyClassImpl<TA, TB, Type>&);
};    

typedef MyClassImpl<float, int, 12> MyFloatIntClass;

template<>
MyFloatIntClass::MyClassImpl()
{
 //
}

template<>
MyFloatIntClass::MyClassImpl( const MyFloatIntClass& rhs )
{
 //
}

template<>
const MyFloatIntClass& MyFloatIntClass::operator=( const MyFloatIntClass& rhs )
{
  return *this;
}

template<>
int MyFloatIntClass::GetType() const
{
   return 22;
}

【讨论】:

  • 我试过了,但这肯定会让情况变得更糟。我想如果我添加模板,编译器会认为我想定义另一个模板。
  • 查看 modelnine 的回答——它比我的要好。
  • @iOSPorter:这些复制器对你有用吗?您需要将 rhs 的类型完全指定为 MyClassImpl 或者您需要一个双模板。
猜你喜欢
  • 1970-01-01
  • 2016-07-13
  • 2014-02-01
  • 1970-01-01
  • 2015-03-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多