我有那个类层次结构:
- 一个枚举类;
- 一个基类(构造函数得到一个枚举类对象);
- 派生自基类的模板类(构造函数得到一个枚举类对象)
我会为模板类的每个实例定义一个 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/