Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instantiating class with template parameter at runtime (C++)?

Tags:

c++

templates

Is it possible to instantiate a class with a template parameter at runtime in the following way?:

#include <iostream>
#include <vector>

using namespace std;

template<typename T>
struct Foo {
  vector<T> d;
};

template<typename T>
struct Solver {
  Foo<T> data;

  virtual void calc() = 0;
};

struct SolverA : Solver<int>
{
  void calc() 
  {
    cout << "PRINT A\n";
  }
};

struct SolverB : Solver<double>
{
  void calc() 
  {
    cout << "PRINT B\n";
  }
};

int main()
{
  ... solver;

  if (...) {
    solver = new SolverA;
  } else {
    solver = new SolverB;
  }

  solver->calc();
}

So classes SolverA and SolverB has no template parameter, but which one just be used cannot be decide at compile time. I tried to used boost::any for this, but I was not sure how to cast than the variable solver to call the function calc(). Any other ideas?

like image 714
Thomas W. Avatar asked Feb 27 '26 13:02

Thomas W.


1 Answers

Add a interface for your class :

#include <iostream>
#include <vector>

using namespace std;

template<typename T>
struct Foo {
  vector<T> d;
};

struct SolverIface
{
  virtual void calc() = 0;
};

template<typename T>
struct Solver : SolverIface {
  Foo<T> data;
};

struct SolverA : Solver<int>
{
  void calc()
  {
    cout << "PRINT A\n";
  }
};

struct SolverB : Solver<double>
{
  void calc()
  {
    cout << "PRINT B\n";
  }
};

int main()
{
  SolverIface *solver;

  if (0) {
    solver = new SolverA;
  } else {
    solver = new SolverB;
  }

  solver->calc();
}

Templates and virtual dispatch do not go along.

like image 111
BЈовић Avatar answered Mar 02 '26 06:03

BЈовић



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!