'Virtual template functions', type erasure, etc. workaround
I want to have a vector of functions which are executed on the same
values and the results put in a vector. Something like this (untested
and simplified) is working:
typedef boost::function<double (double x)> function_type;
std::vector<function_type> vec(2); //Create using lambdas for
simplicity.
using boost::lambda::_1;
vec[0] = _1;
vec[1] = 2 * _1;
//Code to fill results.
double x = 3;
std::vector<double> out(2);
for(int i = 0; i < vec.end(); ++i)
out[i] = vec[i](x);
Now, I realized that what I really need is a templated function.
Think of these as callbacks for now where the caller is a complicated
type. What I want is to be able to use some sort of type erasure or
inheritance for this. I have come to the conclusion that it is not
possible since you can't have virtual template functions, but wanted
to check in for comments.
//The following DOES NOT work, just using as an example for intended
usage.
struct func_parent
{
template<class T>
virtual double operator()(const T& x) = 0;
};
struct my_func1 : func_parent
{
template<class T>
virtual double operator()(const T& t) {...}
};
struct my_func2 : func_parent
{
template<class T>
virtual double operator()(const T& t) {...}
};
//Calling this example
std::vector< func_parent> vec(2); //Ignoring problems with references,
pointers in the vector, etc.
vec[0] = my_func1();
vec[1] = my_func2();
//Code to fill results.
double x = 3; //In reality, this is a complicated callback type, etc.
std::vector<double> out(2);
for(int i = 0; i < vec.end(); ++i)
out[i] = vec[i](x);
Is there any way to get this kind of scenario working? I figure my
last resort is boost::fusion but I am terrified by the compiler error
messages until the variable argument template version is complete.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]