there!
I am trying to create objects from a template class that as an enum as argument.
This is the code:
#include <iostream>
using std::cout;
using std::endl;
#include <string>
using std::string;
class Father
{
public:
string name;
Father(const string &n): name(n) { cout << "Father has been named " << name << endl; }
virtual ~Father(void) { }
virtual void whoami(void) = 0;
};
enum NATION { CANADA, USA, FRANCE, UK };
template<enum NATION nation>
class Son: public Father
{
public:
string nationality;
Son(const string &n): Father(n)
{
switch (nation)
{
case CANADA: nationality = "canadian"; break;
case USA: nationality = "american"; break;
case FRANCE: nationality = "french"; break;
case UK: nationality = "british"; break;
}
cout << "I'm " << nationality << endl;
}
virtual ~Son(void) { }
virtual void whoami(void);
};
template<enum NATION nation>
void Son<nation>::whoami(void) { cout << "My father is " << name << " and I'm " << nationality << endl; }
template<>
void Son<FRANCE>::whoami(void) { cout << "Mon père est " << name << " et je suis français" << endl; }
int main(int, const char *[])
{
Father *canadian = new Son<CANADA>("James");
enum NATION n = FRANCE;
Father *french = new Son<n>("Pierre");
canadian->whoami();
french->whoami();
delete canadian;
delete french;
return 0;
}
The code works well for the Canadian object, but not for the French one!
I get a compilation error on the Son<n>("Pierre"). It says that the template argument is not constant.
Code compiles fine if I replace "n" with "FRANCE" on the constructor invocation.
Is there anyway of doing this without the (silly!) switch option like:
switch(n)
{
case CANADA: pointer = new Son<CANADA>("James"); break;
case USA: pointer = new Son<USA>("James"); break;
case FRANCE: pointer = new Son<FRANCE>("James"); break;
case UK: pointer = new Son<UK>("James"); break;
}