Containers for different signature functions - c++

I'm trying to programming in C++ a framework where the user can indicates a set of functions inside its program where he wants to apply a memoization strategy.
So let's suppose that we have 5 functions in our program f1...f5 and we want to avoid the (expensive) re-computation for the functions f1 and f3 if we already called them with the same input. Notice that each function can have different return and argument types.
I found this solution for the problem, but you can use only double and int.
MY SOLUTION
Ok I wrote this solution for my problem, but I don't know if it's efficient, typesafe or can be written in any more elegant way.
template <typename ReturnType, typename... Args>
function<ReturnType(Args...)> memoize(function<ReturnType(Args...)> func)
{
return ([=](Args... args) mutable {
static map<tuple<Args...>, ReturnType> cache;
tuple<Args...> t(args...);
auto result = cache.insert(make_pair(t, ReturnType{}));
if (result.second) {
// insertion succeeded so the value wasn't cached already
result.first->second = func(args...);
}
return result.first->second;
});
}
struct MultiMemoizator
{
map<string, boost::any> multiCache;
template <typename ReturnType, typename... Args>
void addFunction(string name, function < ReturnType(Args...)> func) {
function < ReturnType(Args...)> cachedFunc = memoize(func);
boost::any anyCachedFunc = cachedFunc;
auto result = multiCache.insert(pair<string, boost::any>(name,anyCachedFunc));
if (!result.second)
cout << "ERROR: key " + name + " was already inserted" << endl;
}
template <typename ReturnType, typename... Args>
ReturnType callFunction(string name, Args... args) {
auto it = multiCache.find(name);
if (it == multiCache.end())
throw KeyNotFound(name);
boost::any anyCachedFunc = it->second;
function < ReturnType(Args...)> cachedFunc = boost::any_cast<function<ReturnType(Args...)>> (anyCachedFunc);
return cachedFunc(args...);
}
};
And this is a possible main:
int main()
{
function<int(int)> intFun = [](int i) {return ++i; };
function<string(string)> stringFun = [](string s) {
return "Hello "+s;
};
MultiMemoizator mem;
mem.addFunction("intFun",intFun);
mem.addFunction("stringFun", stringFun);
try
{
cout << mem.callFunction<int, int>("intFun", 1)<<endl;//print 2
cout << mem.callFunction<string, string>("stringFun", " World!") << endl;//print Hello World!
cout << mem.callFunction<string, string>("TrumpIsADickHead", " World!") << endl;//KeyNotFound thrown
}
catch (boost::bad_any_cast e)
{
cout << "Bad function calling: "<<e.what()<<endl;
return 1;
}
catch (KeyNotFound e)
{
cout << e.what()<<endl;
return 1;
}
}

How about something like this:
template <typename result_t, typename... args_t>
class Memoizer
{
public:
typedef result_t (*function_t)(args_t...);
Memoizer(function_t func) : m_func(func) {}
result_t operator() (args_t... args)
{
auto args_tuple = make_tuple(args...);
auto it = m_results.find(args_tuple);
if (it != m_results.end())
return it->second;
result_t result = m_func(args...);
m_results.insert(make_pair(args_tuple, result));
return result;
}
protected:
function_t m_func;
map<tuple<args_t...>, result_t> m_results;
};
Usage is like this:
// could create make_memoizer like make_tuple to eliminate the template arguments
Memoizer<double, double> memo(fabs);
cout << memo(-123.456);
cout << memo(-123.456); // not recomputed

It's pretty hard to guess at how you're planning to use the functions, with or without memoisation, but for the container-of-various-function<>s aspect you just need a common base class:
#include <iostream>
#include <vector>
#include <functional>
struct Any_Function
{
virtual ~Any_Function() {}
};
template <typename Ret, typename... Args>
struct Function : Any_Function, std::function<Ret(Args...)>
{
template <typename T>
Function(T& f)
: std::function<Ret(Args...)>(f)
{ }
};
int main()
{
std::vector<Any_Function*> fun_vect;
auto* p = new Function<int, double, double, int> { [](double i, double j, int z) {
return int(i + j + z);
} };
fun_vect.push_back(p);
}

The problem with this is how to make it type-safe. Look at this code:
MultiMemoizator mm;
std::string name = "identity";
mm.addFunction(name, identity);
auto result = mm.callFunction(name, 1);
Is the last line correct? Does callFunction have the right number of parameters with the right types? And what is the return type?
The compiler has no way to know that: it has no way of understanding that name is "identity" and even if it did, no way to associate that with the type of the function. And this is not specific to C++, any statically-typed language is going to have the same problem.
One solution (which is basically the one given in Tony D's answer) is to tell the compiler the function signature when you call the function. And if you say it wrong, a runtime error occurs. That could look something like this (you only need to explicitly specify the return type, since the number and type of parameters is inferred):
auto result = mm.callFunction<int>(name, 1);
But this is inelegant and error-prone.
Depending on your exact requirements, what might work better is to use "smart" keys, instead of strings: the key has the function signature embedded in its type, so you don't have to worry about specifying it correctly. That could look something like:
Key<int(int)> identityKey;
mm.addFunction(identityKey, identity);
auto result = mm.callFunction(identityKey, 1);
This way, the types are checked at compile time (both for addFunction and callFunction), which should give you exactly what you want.
I haven't actually implemented this in C++, but I don't see any reason why it should be hard or impossible. Especially since doing something very similar in C# is simple.

you can use vector of functions with signature like void someFunction(void *r, ...) where r is a pointer to result and ... is variadic argument list. Warning: unpacking argument list is really inconvenient and looks more like a hack.

At first glance, how about defining a type that has template arguments that differ for each function, i.e.:
template <class RetType, class ArgType>
class AbstractFunction {
//etc.
}
have the AbstractFunction take a function pointer to the functions f1-f5 with template specializations different for each function. You can then have a generic run_memoized() function, either as a member function of AbstractFunction or a templated function that takes an AbstractFunction as an argument and maintains a memo as it runs it.
The hardest part will be if the functions f1-f5 have more than one argument, in which case you'll need to do some funky things with arglists as template parameters but I think C++14 has some features that might make this possible. An alternative is to rewrite f1-f5 so that they all take a single struct as an argument rather than multiple arguments.
EDIT: Having seen your problem 1, the problem you're running into is that you want to have a data structure whose values are memoized functions, each of which could have different arguments.
I, personally, would solve this just by making the data structure use void* to represent the individual memoized functions, and then in the callFunction() method use an unsafe type cast from void* to the templated MemoizedFunction type you need (you may need to allocate MemoizedFunctions with the "new" operator so that you can convert them to and from void*s.)
If the lack of type safety here irks you, good for you, in that case it may be a reasonable option just to make hand-written helper methods for each of f1-f5 and have callFunction() dispatch one of those functions based on the input string. This will let you use compile-time type checking.
EDIT #2: If you are going to use this approach, you need to change the API for callFunction() slightly so that callFunction has template args matching the return and argument types of the function, for example:
int result = callFunction<int, arglist(double, float)>("double_and_float_to_int", 3.5, 4);
and if the user of this API ever types the argument type or return types incorrectly when using callFunction... pray for their soul because things will explode in very ugly ways.
EDIT #3: You can to some extent do the type checking you need at runtime using std::type_info and storing the typeid() of the argument type and return type in your MemoizedFunction so that you can check whether the template arguments in callFunction() are correct before calling - so you can prevent the explosion above. But this will add a bit of overhead every time you call the function (you could wrap this in a IF_DEBUG_MODE macro to only add this overhead during testing and not in production.)

Related

Is it possible to forward function calls with matching template type for a std::any-like container?

I haven't found a way to achieve what I want but I'm not knowledgeable enough to know if its impossible. Help would be appreciated.
The main data data container in our software behaves a bit like a std::variant or std::any: It has a base class BaseContainer that provides a type enum. The derived instance DataContainer holds the actual data in a typed tensor member variable. So a simplified example boils down to something like this:
BaseContainer* vContainer = new DataContainer<float>({1000000});
if (vContainer->getType() == DataTypes::FLOAT)
const Tensor<float>& vTensor = dynamic_cast<DataContainer<float>>(vContainer)->getData();
We have many methods that process data based on the underlying templated type and dimensions:
template<typename T>
void processData(const tensor<T>& aTensor, ...other arguments...);
The problem is, for every method like processData() that we want to call with a BaseContainer, we need to write a binding method that unravels the possible types to call the typed version of processData():
void processData(BaseContainer* aContainer) {
switch (vContainer->getType()) {
case DataTypes::INT8:
return processData(dynamic_cast<DataContainer<int8_t>>(vContainer)->getData());
case DataTypes::UINT8:
return processData(dynamic_cast<DataContainer<uint8_t>>(vContainer)->getData());
case DataTypes::INT16:
return processData(dynamic_cast<DataContainer<int16_t>>(vContainer)->getData());
case DataTypes::UINT16:
return processData(dynamic_cast<DataContainer<uint16_t>>(vContainer)->getData());
...
default:
throw(std::runtime_error("Type not supported"));
}
}
My question is: Is it possible to make a single "adapter" method (in any released version of c++) that can take a function (like processData()), a BaseContainer and potentially a list of arguments, and invoke the correct template binding of this function with the arguments?
I failed to bind a template function dynamically because I was not able to pass the name without the template type. Yet the template type would need to be dynamic based on the BaseContainer. But maybe there are other means to achieve what I want to do? I'm very curious about any solution, mostly also to extend my understanding, as long as the complexity of the solution is below writing hundreds of adapter methods.
If nothing else, would it be possible to generate the "adapter" methods using preprocessor macros?
You cannot pass overloads by name, but you can pass functor with overloaded operator() as generic lambda have.
So
template <typename F>
auto dispatch(BaseContainer& vContainer, F f) {
switch (vContainer.getType()) {
case DataTypes::INT8:
return f(dynamic_cast<DataContainer<int8_t>&>(vContainer).getData());
case DataTypes::UINT8:
return f(dynamic_cast<DataContainer<uint8_t>&>(vContainer).getData());
case DataTypes::INT16:
return f(dynamic_cast<DataContainer<int16_t>&>(vContainer).getData());
case DataTypes::UINT16:
return f(dynamic_cast<DataContainer<uint16_t>&>(vContainer).getData());
...
default:
throw (std::runtime_error("Type not supported"));
}
}
with usage
dispatch(vContainer, [](auto* data){ return processData(data); });
If you are willing to write a small wrapper class for each processData-like function, you could do something like this:
// One like this for each function.
struct ProcessDataWrapper {
template <typename... Args>
static auto run(Args&&... args) {
return processData(std::forward<Args>(args)...);
}
};
template <typename Wrapper>
auto ProcessGeneric(BaseContainer* aContainer) {
switch (vContainer->getType()) {
case DataTypes::INT8:
return Wrapper::run(dynamic_cast<DataContainer<int8_t>>(vContainer)->getData());
// ...
}
// Called as
ProcessGeneric<ProcessDataWrapper>(myContainer);
It is possible, but as the comments say, it might be worth conidering std::visit.
Here's a solution requiring c++17 that only requires two lines for each function template you want to wrap. You could use a simple macro to simplify the wrpping further.
The core idea is to have a cast function that maps from a DataType enum to the correspondng DataContainer and then to leverage c++17 fold expressions to wrap the switch statement in your code.
Here's the cast function, so we have exactly one place to map from DataType to the actiual DataContainer:
template<DataType t>
constexpr inline decltype(auto) cast(BaseContainer& c) {
if constexpr(t == INT) return static_cast<DataContainer<int>&>(c);
else if constexpr(t == FLOAT) return static_cast<DataContainer<float>&>(c);
... map all other enum values ...
}
This is rather a convenience helper to make the following code a bit more readable. The next code block uses the c++17 fold expression to dispatch the function based on the type of the container.
template<DataType... types>
auto dispatcher_impl = [](auto f) {
// NB: capture by value here only for sake of readbility.
return [=](BaseContainer& c, auto... args) {
([&]{ if(c.GetDataType() == types ) { std::invoke(f, cast<types>(c), args...); return true; } return false; }() || ...);
};
};
auto data_type_dispatcher = [](auto f) {
return dispatcher_impl<INT, FLOAT, ... other types here ...>(f);
};
The core idea is to wrap the function into a lambda that checks the DataContainer's DataType and calls the function only if it matches. The Fold expression over the || operator is used to unpack the DataTypes.
Usage example:
template<typename T>
void processData(DataContainer<T>& c, int arg) {
if constexpr(std::is_same_v<T, int>) std::cout << "int";
else if constexpr(std::is_same_v<T, float>) std::cout << "float";
std::cout << ", arg: " << arg << '\n';
}
// This needs to be done for each function:
auto pd = data_type_dispatcher([](auto& c, int arg) { processData(c, arg); });
int main() {
DataContainer<float> f;
DataContainer<int> i;
pd(f, 2); // prints float, 2
pd(i, 4); // prints int, 4
}
Full example here.
In order to throw an exception if the type is not supported, simply add a lambda that throws at the end of the fold expression:
([&]{ if(c.GetDataType() == types ) { std::invoke(f, cast<types>(c), args...); return true; } return false; }() || ... || []() -> bool{ throw (std::runtime_error("Type not supported")); }());
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

C++ Templated Delegates like Unity

after saw Unity's delegates and events, i'm trying to code my own:
I want to create a class with a variadic template, to specify the return type of the functions, and optionals arguments.
template <typename Ret, typename... Args>
class MyDelegate{
std::vector<Ret(*)(Args...)> vec;
public:
void operator+=( const Ret(*)(Args...)& newElement)
{
vec.push_back(newElement);
}
Ret operator()(const Args&... args)
{
for (auto i = vec.begin(); i != vec.end(); ++i)
(*i)(args...);
}
};
As you can see, i would like this class to be used this way:
MyDelegate<void> voidDelegate;
MyDelegate<void, int> intDelegate;
MyDelegate<int, char, boolt> miscDelegate;
and "adding" functions to each one using += operators, like:
voidDelegate += voidFunc;
//etc...
I'm having problem with the += operator for now, because VS don't accept this:
MyDelegate<void, int> delegate1;
delegate1 += [](const int a)->void{std::cout << a << std::endl; };
The lambda function is correct: it take an int and return void, so i don't understand whats' wrong.
The issue is that your std::vector stores function pointers. It doesn't store std::bind objects, it doesn't store member functions, it doesn't store functors and it doesn't store lambdas. You are trying to add a lambda to it, hence the failure.
If you want to store any kind of object which supports calling with the correct argument and return types, you want std::function:
using FunType = std::function<Ret(Args...)>;
std::vector<FunType> vec;
Demo
Incidentally, you could improve your solution by perfect-forwarding your operator() args and copying your newElement arg in the interface and moving it into the std::vector.
Your delegate accepts only function pointers. A lambda is not a function pointer. However, the lambda that you are trying to doesn't capture anything. Which means that it can be converted to a function pointer thanks to some sorcery:
MyDelegate<void, int> delegate1;
delegate1 += +[](const int a)->void{std::cout << a << std::endl; };
↑↑↑
However, once you want to allow functors that have member variables, the extra + won't work:
delegate1 += +[x](const int a) { ... }; // error: no match for operator+
At which point you'll definitely have to use TartanLlama's suggestions of std::function.
#TartanLlama's right, std::function is what you need.
And the calling loop can be folded to for (auto handler : vec) handler(args...);

Data type calling template method

How do I use different data types without the overhead of writing a line of code for each type?
Say if there's a template method that takes any data type.
And I want to pass in various data types (int, double, string, char, ...etc) without creating a line for each data type.
Is there an efficient way of looping through different data types and call the template method for each data type??
Sample Code:
template <typename T>
sorted_vector<T>::sorted_vector( sorted_vector<value_type> const& rhs )
: beg_( new value_type [rhs.size()] )
, end_( beg_ + rhs.size() )
, cap_( end_ )
{
std::copy( rhs.beg_, rhs.end_, beg_ );
}
So my task is to test the template with bugs but wanted to check all value_types.
And I wanted to test a vector, vector, vector, etc etc
You may loop using variadic template:
class Test
{
public:
template <typename T>
static void f()
{
// Your generic code to execute
std::cout << typeid(T).name() << std::endl;
}
};
template<typename F, typename ... Ts>
void Call()
{
std::initializer_list<int>({ (F::template f<Ts>(), 0)... });
}
And then call it that way:
Call<Test, int, char, char*>();
But I'm not sure it is more clear than
// Equivalent to
Test::f<int>();
Test::f<char>();
Test::f<char*>();
It is difficult to understand what you are really asking as your question is too broad. I would recommend to look into boost::variant and especially how pattern 'visitor' is implemented there. It does not mean you have to use exactly this library, but this could be a good start point how to implement such logic. Other candidates would be std::tuple and boost::any
Sound like a case for Template Metaprogramming.
Look at the foreach of Boost's MPL: foreach
Their example does something like you try to do: Calling a functor for different types and values of a list.
struct value_printer
{
template< typename U > void operator()(U x)
{
std::cout << x << 'n';
}
};
int main()
{
for_each< range_c<int,0,10> >( value_printer() );
}

How to recover the type of a function pointer at runtime

In the code I register one or multiple function pointer in a manager class.
In this class I have a map that maps the argument types of the function to said function. It may look like so: std::map< std::vector<std::type_index> , void*>
template<typename Ret, typename... Args>
void Register(Ret(*function)(Args...)) {
void* v = (void*)function;
// recursively build type vector and add to the map
}
At runtime the code gets calls (from an external script) with an arbitrary number of arguments. These arguments can be read as primitive data types or as custom types that will be specified at compile time.
With every call from the script, I have to find out which function to call, and then call it. The former is easy and already solved (filling a vector with type_index in a loop), but I can't think of a solution for the latter.
My first approach was using variadic templates in recursion with an added template argument for each read type - but this turned out to be impossible since templates are constructed at compile time, and the arbitrary number of arguments is read at runtime.
Without variadic templates however, I don't see any possibility to achieve this. I considered boost::any instead of void*, but I didn't see how that would solve the need to cast back to the original type. I also thought of using std::function but that would be a templated type, so it could not be stored in a map for functions with different arguments.
(If it's unclear what I'm asking, think of LuaBinds possibility to register overloaded functions. I tried to understand how it's implemented there (without variadic templates, pre-C++11), but to no avail.)
Suppose you had the arguments in a vector of some kind, and a known function (fully).
You can call this. Call the function that does this invoke.
Next, work out how to do this for template<class... Args>. Augment invoke.
So you have written:
typedef std::vector<run_time_stuff> run_time_args;
template<class... Args>
void invoke( void(*func)(Args...), run_time_args rta )
at this point. Note that we know the types of the argument. I do not claim the above is easy to write, but I have faith you can figure it out.
Now we wrap things up:
template<class...Args>
std::function<void(run_time_args)> make_invoker(void(*func)(Args...)){
return [func](run_time_args rta){
invoke(func, rta);
};
}
and now instead of void* you store std::function<void(run_time_args)> -- invokers. When you add the function pointers to the mechanism you use make_invoker instead of casting to void*.
Basically, at the point where we have the type info, we store how to use it. Then where we want to use it, we use the stored code!
Writing invoke is another problem. It will probably involve the indexes trick.
Suppose we support two kinds of arguments -- double and int. The arguments at run time are then loaded into a std::vector< boost::variant<double, int> > as our run_time_args.
Next, let us extend the above invoke function to return an error in the case of parameter type mismatch.
enum class invoke_result {
everything_ok,
error_parameter_count_mismatch,
parameter_type_mismatch,
};
typedef boost::variant<int,double> c;
typedef std::vector<run_time_stuff> run_time_args;
template<class... Args>
invoke_result invoke( void(*func)(Args...), run_time_args rta );
now some boilerplate for the indexes trick:
template<unsigned...Is>struct indexes{typedef indexes type;};
template<unsigned Max,unsigned...Is>struct make_indexes:make_indexes<Max-1, Max-1,Is...>{};
template<unsigned...Is>struct make_indexes<0,Is...>:indexes<Is...>{};
template<unsigned Max>using make_indexes_t=typename make_indexes<Max>::type;
With that, we can write an invoker:
namespace helpers{
template<unsigned...Is, class... Args>
invoke_result invoke( indexes<Is...>, void(*func)(Args...), run_time_args rta ) {
typedef void* pvoid;
if (rta.size() < sizeof...(Is))
return invoke_result::error_parameter_count_mismatch;
pvoid check_array[] = { ((void*)boost::get<Args>( rta[Is] ))... };
for( pvoid p : check_array )
if (!p)
return invoke_result::error_parameter_type_mismatch;
func( (*boost::get<Args>(rts[Is]))... );
}
}
template<class... Args>
invoke_result invoke( void(*func)(Args...), run_time_args rta ) {
return helpers::invoke( make_indexes_t< sizeof...(Args) >{}, func, rta );
}
And that should work when func's args exactly match the ones passed in inside run_time_args.
Note that I was fast and loose with failing to std::move that std::vector around. And that the above doesn't support implicit type conversion. And I didn't compile any of the above code, so it is probably littered with typos.
I was messing around with variadic templates a few weeks ago and came up with a solution that might help you.
DELEGATE.H
template <typename ReturnType, typename ...Args>
class BaseDelegate
{
public:
BaseDelegate()
: m_delegate(nullptr)
{
}
virtual ReturnType Call(Args... args) = 0;
BaseDelegate* m_delegate;
};
template <typename ReturnType = void, typename ...Args>
class Delegate : public BaseDelegate<ReturnType, Args...>
{
public:
template <typename ClassType>
class Callee : public BaseDelegate
{
public:
typedef ReturnType (ClassType::*FncPtr)(Args...);
public:
Callee(ClassType* type, FncPtr function)
: m_type(type)
, m_function(function)
{
}
~Callee()
{
}
ReturnType Call(Args... args)
{
return (m_type->*m_function)(args...);
}
protected:
ClassType* m_type;
FncPtr m_function;
};
public:
template<typename T>
void RegisterCallback(T* type, ReturnType (T::*function)(Args...))
{
m_delegate = new Callee<T>(type, function);
}
ReturnType Call(Args... args)
{
return m_delegate->Call(args...);
}
};
MAIN.CPP
class Foo
{
public:
int Method(int iVal)
{
return iVal * 2;
}
};
int main(int argc, const char* args)
{
Foo foo;
typedef Delegate<int, int> MyDelegate;
MyDelegate m_delegate;
m_delegate.RegisterCallback(&foo, &Foo::Method);
int retVal = m_delegate.Call(10);
return 0;
}
Not sure if your requirements will allow this, but you could possibly just use std::function and std::bind.
The below solution makes the following assumptions:
You know the functions you want to call and their arguments
The functions can have any signature, and any number of arguments
You want to use type erasure to be able to store these functions and arguments, and call them all at a later point in time
Here is a working example:
#include <iostream>
#include <functional>
#include <list>
// list of all bound functions
std::list<std::function<void()>> funcs;
// add a function and its arguments to the list
template<typename Ret, typename... Args, typename... UArgs>
void Register(Ret(*Func)(Args...), UArgs... args)
{
funcs.push_back(std::bind(Func, args...));
}
// call all the bound functions
void CallAll()
{
for (auto& f : funcs)
f();
}
////////////////////////////
// some example functions
////////////////////////////
void foo(int i, double d)
{
std::cout << __func__ << "(" << i << ", " << d << ")" << std::endl;
}
void bar(int i, double d, char c, std::string s)
{
std::cout << __func__ << "(" << i << ", " << d << ", " << c << ", " << s << ")" << std::endl;
}
int main()
{
Register(&foo, 1, 2);
Register(&bar, 7, 3.14, 'c', "Hello world");
CallAll();
}

Create functors from functions with unknown argument count

I wrote a program in C++ & boost. Is it possible to write a template class producing functors from functions with an unknown number of arguments, e.g. my_call<func>(vector<variant>), where fun can be bool fun(string) or bool fun(int, int, string), etc.?
First, it is important to recognize that boost::variant<> is a class template that requires the list of all the possible types it can hold. So, you won't have just a vector<variant>, but rather a vector<variant<string, double>>, or vector<variant<int, double, string, my_class>>, and you won't be able to mix them.
This made me think you might want to use boost::any rather than boost::variant<>. Thus, I present here a solution that works with boost::variant and can be slightly modified to use boost::any, so you can pick the version you prefer.
To begin with, I must admit that the solution is simple to use but not so simple to understand, so I will have to introduce some machinery first. This machinery is common to both the variant-based and the any-based solution.
//=============================================================================
// META-FUNCTIONS FOR CREATING INDEX LISTS
// The structure that encapsulates index lists
template <size_t... Is>
struct index_list
{
};
// Collects internal details for generating index ranges [MIN, MAX)
namespace detail
{
// Declare primary template for index range builder
template <size_t MIN, size_t N, size_t... Is>
struct range_builder;
// Base step
template <size_t MIN, size_t... Is>
struct range_builder<MIN, MIN, Is...>
{
typedef index_list<Is...> type;
};
// Induction step
template <size_t MIN, size_t N, size_t... Is>
struct range_builder : public range_builder<MIN, N - 1, N - 1, Is...>
{
};
}
// Meta-function that returns a [MIN, MAX) index range
template<size_t MIN, size_t MAX>
using index_range = typename detail::range_builder<MIN, MAX>::type;
The meta-class index_range allows defining compile-time sequences of integers. An interesting proposal have been made by Jonathan Wakely to standardize this kind of construct, so that this whole machinery would not be needed. For the moment, however, we have to hand code this as done above.
Now that we can build compile-time integer sequences, we can exploit variadic templates and argument unpacking to create a dispatching mechanism that translates a vector of variant arguments into a regular argument list. Notice how the concrete variant<> type must be provided as a template argument. This will not be needed for the solution based on any.
// Headers needed for the implementation of the dispatcher
#include <vector>
#include <functional>
#include <boost/variant.hpp>
// Just for convenience
using namespace std;
using boost::variant;
//============================================================================
// DISPATCHER IMPLEMENTATION
// Call dispatching mechanism: notice how the underlying variant type
// must be provided as a template argument (the first one)
template<typename VT, typename R, typename... Args>
struct dispatcher
{
template<typename F>
dispatcher(F f) : _f(f) { }
// The call operator which performs the variant dispatch
R operator () (vector<VT> const& v)
{
if (v.size() != sizeof...(Args))
{
// Wrong number of arguments provided!
return false;
}
// Delegates to internal function call: needed for deducing
// a sequence of integers to be used for unpacking.
index_range<0, sizeof...(Args)> indexes;
return do_call(v, indexes);
}
private:
// The heart of the dispatching mechanism
template<size_t... Is>
R do_call(vector<VT> const& v, index_list<Is...> indexes)
{
return _f((get_ith<Args>(v, Is))...);
}
// Helper function that extracts a typed value from the variant.
template<typename T>
T get_ith(vector<VT> const& v, size_t i)
{
return boost::get<T>(v[i]);
}
// Wrapper that holds the function to be invoked.
function<R(Args...)> _f;
};
// Helper function that allows deducing the input function signature
template<typename VT, typename R, typename... Args>
function<R (vector<VT> const&)> get_dispatcher(R (*f)(Args...))
{
dispatcher<VT, R, Args...> d(f);
return d;
}
Finally, a short demonstration of how you could use this. Suppose we have two test functions such as the ones below:
#include <iostream>
bool test1(string s, double d)
{
cout << s << " " << d << endl;
return true;
}
bool test2(int i1, int i2, string s1, string s2)
{
cout << i1 << " " << i2 << " " << s1 << " " << s2 << endl;
return true;
}
What we want is to invoke them by building a vector of variants and have it dispatched to the desired function. Once again, I must stress the fact that we need to specify the list of all the types our variant can hold. Here, I will assume these types are string, double, and int, but your program might work with different ones.
Also, the solution is based on std::function<> for realizing the type erasure that allows you creating functors of different types and yet invoke them uniformly. Thus, a convenience type definition for this std::function<> (which in turn depends on the variant<> type we use) is provided as well:
int main()
{
// A helper type definition for the variant
typedef variant<int, double, string> vt;
// A helper type definition for the function wrapper
typedef function<bool (vector<vt>)> dispatcher_type;
// Get a caller for the first function
dispatcher_type f1 = get_dispatcher<vt>(test1);
// Prepare arguments for the first function
vector<vt> v = {"hello", 3.14};
// Invoke the first function
f1(v);
// Get a caller for the second function
dispatcher_type f2 = get_dispatcher<vt>(test2);
// Prepare arguments for the second function
v.assign({1, 42, "hello", "world"});
// Invoke the second function
f2(v);
}
Since all dispatchers have type dispatcher_type, you can easily put them into a container. However, you must be aware of the fact that attempts to invoke a function with the wrong number of arguments will be detected only at run-time (it is impossible to know at compile-time how many elements an std::vector<> contains). Thus, proper care must be taken.
As promised, I will now slightly modify this solution to use boost::any rather than boost::variant. The advantage is that since boost::any can hold any value, it is not necessary to specify the list of the possible types which can be used as function arguments.
While the helper machinery is unchanged, the core dispatcher class template must be modified as follows:
#include <vector>
#include <functional>
#include <boost/any.hpp>
using namespace std;
using boost::any;
//=============================================================================
// DISPATCHER IMPLEMENTATION
template<typename R, typename... Args>
struct dispatcher
{
template<typename F>
dispatcher(F f) : _f(f) { }
// The call operator which performs the dispatch
R operator () (vector<any> const& v)
{
if (v.size() != sizeof...(Args))
{
// Wrong number of arguments provided!
return false;
}
// Delegates to internal function call: needed for deducing
// a sequence of integers to be used for unpacking.
index_range<0, sizeof...(Args)> indexes;
return do_call(v, indexes);
}
private:
// The heart of the dispatching mechanism
template<size_t... Is>
R do_call(vector<any> const& v, index_list<Is...> indexes)
{
return _f((get_ith<Args>(v, Is))...);
}
// Helper function that extracts a typed value from the variant.
template<typename T>
T get_ith(vector<any> const& v, size_t i)
{
return boost::any_cast<T>(v[i]);
}
// Wrapper that holds the function to be invoked.
function<R(Args...)> _f;
};
// Helper function
template<typename R, typename... Args>
function<R (vector<any> const&)> get_dispatcher(R (*f)(Args...))
{
dispatcher<R, Args...> d(f);
return d;
}
As you see, the VT template argument has vanished. In particular, it is possible to call get_dispatcher without explicitly specifying any template argument. Using the same test functions we have defined for the variant-based solution, here is how you would adapt the main() routine:
int main()
{
// Helper type definition
typedef function<bool (vector<any>)> dispatcher_type;
// Get a caller for the first function
dispatcher_type f1 = get_dispatcher(test1);
// Get a caller for the second function
dispatcher_type f2 = get_dispatcher(test2);
// Prepare arguments for the first function
vector<any> v = {string("hello"), 3.14};
// Invoke the first function
f1(v);
// Prepare arguments for the second function
v.assign({1, 42, string("hello"), string("world")});
// Invoke the second function
f2(v);
}
The only disadvantage is that with boost::any you cannot assign string literals explicitly, because string literals are of type char [], and arrays cannot be used to initialize objects of type any:
any a = "hello"; // ERROR!
Thus, you have to either wrap them into string objects, or explicitly convert them to a pointer to char const*:
any a = string("hello"); // OK
any b = (char const*)"hello"; // OK
If this is not a huge problem for you, it's probably better to go for this second solution.