jeudi 10 octobre 2019

Instantiate C++ template class without parameter / depending on type in if-statement

I wrote different function objects A, B, and C in C++ and I want to instantiate a template class with one of the function objects, depending on the user input. But as it seems there is no way to instantiate only one of the types in an if statement, is it?

If I try to instantiate one class with a template in the if statement, the g++ compiler gives me a "use of undeclared identifier 'bkt'"-error. If I instantiate it beforehand, the class destroys itself when leaving the if-statement.

Here's my code:

class A {
public: void operator()(int a) {}
}; 

class B {
public: void operator()(int a) {}
}; 

class C {
public: void operator()(int a) {}
}; 

template <typename T>
class MyClass {
public:
  MyClass<T>(const std::string &file);
  ~MyClass<T>;

private:
  T m_func;

int doStuff(int a) {
  return m_func(a);
 }
};

int main() {

std::string filename = std::string(argv[1]);
std::getline(std::cin, metric);

if (metric == "A") {
  MyClass<A> foo(filename);
}
else if (metric == "B") {
  MyClass<B> foo(filename);
}
else {
  MyClass<C> foo(filename);
}

int a = 1;
foo.doStuff(int a); // undeclared identifier "foo"

getchar();
return 0;
}

I know, that I somehow have to declare the foo-variable, but I was hoping the compiler might be ok with it because one of the cases of the if-statement will happen anyways. Obviously it's not, so what can I do in order to not instantiate every single type?

Aucun commentaire:

Enregistrer un commentaire