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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With