【问题标题】:Template specialization implementation in cpp file causes template-id does not match errorcpp 文件中的模板特化实现导致模板 ID 不匹配错误
【发布时间】:2014-06-25 00:40:20
【问题描述】:

考虑以下代码:

class Bar;

enum Values
{
  ValA,
  ValB, // ...
};

template< typename T >
struct Foo : virtual public Bar
{
};

template<>
struct Foo< ValA >
{
  void doSomething();
};

如果我在头文件中定义doSomething()的实现,当我使用Foo::doSomething()时程序不会报错。但是,如果我将实现移动到一个 cpp 文件,如下所示,我得到一个错误:

template<>
void Foo< ValA >::doSomething()
{
  // ...
}

错误:

error: template-id 'doSomething<>' for 'void Foo<(Values)0u>::doSomething()' does not match any template declaration.

我不确定为什么会失败。我相信将专门的实现移动到 cpp 文件应该不是问题。我以前做过。

【问题讨论】:

标签: c++ templates constructor virtual


【解决方案1】:

有几个问题。

@dyp 在 cmets 部分针对您的问题指出了一个问题。你需要使用:

void Foo< ValA >::doSomething()
{
}

而不是

template<>
void Foo< ValA >::doSomething()
{
}

另一个是你必须将类模板更改为:

template< int T >
struct Foo : virtual public Bar
{
};

如果您使用 typename 作为模板参数,则无法使用 ValA 创建 Foo 的特化。

【讨论】:

  • 为什么不用枚举作为非类型模板参数的类型呢?
  • 酷。谢谢你的回答。使用 typename 关键字是一个错字。我的意思是改用枚举的名称。
猜你喜欢
  • 2016-08-05
  • 2011-04-25
  • 1970-01-01
  • 2015-02-03
  • 2022-06-18
  • 1970-01-01
  • 2021-07-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多