简体   繁体   中英

typedef template class instances

I've that class hierarchy:

  • an enum class;
  • a base class (the constructor get an enum class object);
  • a template class derived from base (the constructor get an enum class object)

I would define a typedef for each instance of the template class. Each instance of the template class takes as a parameter an element of enum class. Here's the code:

#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;
}

I'm trying to compile this example with Code::Blocks (13.12) on Windows and I get those errors: - error: type/value mismatch at argument 1 in template parameter list for
'template class instrument'| - error: expected a type, got 'piano'|

Taks for any suggestion.

instrument_name::piano is not a type. Hence, you cannot use:

typedef instrument<instrument_name::piano> Piano;

You can use:

// 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;

The template expects a type, not a value. Your error message explains this well, you just have to read it carefully.

You can fix this by using instrument_name instead of class in the template.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM