C++ Store an expression template inside a class whose objects will be part of a vector
Solution 1:
I see you have improved your question. Yes there are debatably better solutions.
One nice solution the std lib offers you, is to use type-erasure using std:function
.
#include <vector>
#include <functional>
#include <iostream>
#include <cmath>
struct FunctorTypeA {
double a;
FunctorTypeA(const double ap): a(ap) {}
auto operator()([[maybe_unused]]const double x) const { return a;}
};
int main(){
auto funcVec{std::vector<std::function<double(double)>>{}};
funcVec.push_back(FunctorTypeA{3.14}); // functor allowed
funcVec.push_back([](double x){return x;}); // lambda allowed
funcVec.push_back(sqrt); // function pointer allowed, e.g. C math function
for(auto&& f:funcVec){
std::cout << f(2.0) << '\n';
}
}
This way you don't complicate things with inheritance and pointer casting. Easy to make mistakes there. std::vector
and std::function
will do all the cleaning up. (That was something you can easily miss in your vector-of-pointers solution)
Note: std::function
may perform a dynamic allocation. But so does std::vector
and inheritance has vtable overhead.