c++ - typedef 模板类实例

标签 c++ templates enums

我有那个类层次结构:

  • 一个枚举类;
  • 一个基类(构造函数得到一个枚举类对象);
  • 派生自基类的模板类(构造函数得到一个枚举类对象)

我会为模板类的每个实例定义一个 typedef。 模板类的每个实例都将枚举类的一个元素作为参数。 这是代码:

#include <iostream>
using namespace std;
enum class instrument_name { none = 0, piano, guitar, trumpet, saxophone} ;
class instrument_base
{
public:
instrument_base(instrument_name name): _name(name)
{
cout << "I'm base class" << endl;
}
virtual ~instrument_base(){}
// other functions

private:
instrument_name _name;
};

template<class T>
class instrument : public instrument_base
{
public:
instrument(instrument_name name):instrument_base(name)
{
cout << "I'm template class" << endl;
}
};

typedef instrument<instrument_name::piano> Piano;    // error
typedef instrument<instrument_name::guitar> Guitar;    // error
typedef instrument<instrument_name::trumpet> Trumpet;    // error
typedef instrument<instrument_name::saxophone> Saxophone;    // error

int main()
{
cout << "Hello Instruments!" << endl;

Piano p;
Guitar g;
Trumpet tr;
Saxophone s;

return 0;
}

我正在尝试在 Windows 上使用 Code::Blocks (13.12) 编译此示例 我得到了这些错误: - 错误:
的模板参数列表中参数 1 的类型/值不匹配 '模板类仪器'| - 错误:需要一个类型,得到“钢琴”|

接受任何建议。

最佳答案

instrument_name::piano 不是类型。因此,您不能使用:

typedef instrument<instrument_name::piano> Piano;

您可以使用:

// Use a non-type template parameter.
template <instrument_name i_name>
class instrument : public instrument_base
{
   public:
      instrument():instrument_base(i_name)
   {
      cout << "I'm template class" << endl;
   }
};

typedef instrument<instrument_name::piano> Piano;
Piano p;

关于c++ - typedef 模板类实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32532843/

相关文章:

c++ - 使用 Arduino 将位置编码器值转换为 RPM 时出现问题

c++ - 为什么不能将互斥量传递给线程?

php - 如何将变量从父模板传递到 Twig 中的子模板?

java - 枚举,增强的 for 循环

c++ - 使用 OpenMP C++ 并行化程序以计算积分

c++ - 解码抛出的 C++ 异常的参数 (0xE06D7363)

c++ - 友元函数中的类型不完整

c++ - 为什么编译器在赋值时调用模板化的复制构造函数?

c# - 使用枚举作为变量(?)

ios - Swift - Enum 接受一个整数并确定范围