I want to know if it is possible to use the number of arguments passed to a variadic template as placeholder in a boost::bind call.
Something like this:
template <typename ... Args>
boost::bind(&function, this, anArg, _1)); //If Args count equals 1
boost::bind(&function, this, anArg, _1, _2)); //If Args count equals 2
boost::bind(&function, this, anArg, _1, _2, _3)); //If Args count equals 3
Is this possible?
Thank you
Using _1, _2, ... directly is not possible with variadic template. You need to use expansive macros instead.
However, you can wrap theses placeholders in a templated factory to get _1 with the template argument 1, _2 for 2, etc ...
Implementations such as gcc / msvc already define placeholders as templated struct (respectively std::_Placeholder and std::_Ph) so you can define you factory this way:
This defined, you can expand a parameter pack with all the placeholders you want :
So the following code will output "calling:10 c 42 a"
Using tricks like make_indice will grant you the possibility to achieve you original goal.
There definitely is a way with partial specialization. your variadic doesn't know the number of arguments right away right ? you have to use compile-time recursion, during this time you can stack your arguments using boost::mpl (or count them using a simple integral constant increment). then in your last non-variadic recursion call (with 0 arg) you call mpl::size on your container (or just use the integral counter if you chose that way) to call a Callable like the other answer, that bears all the arguments, plus one integral template paramater at the beginning of the type list. and that is what you specialize. you make a caller for each number of arguments that will call the correct bind according to its specialized number of arguments. (the Callable structures are (partially) specialized according to the number of argument integral template parameter. and even though the Call function takes the max number of argument, it only wraps the correct boost::bind call for example the bind(..,_1,_2) for the Callable<2, T1, T2, T3>) its not terrible, but I confirm that I have used this approach in C++03 in the past.
This is not an answer to the specific problem, but a nice workaround for the problem you are likely trying to solve.
I ran into the same issue when implementing a generic delegate mechanism. My solution was to use a wrapper on top of just the bind call, specializing that for the variations. While it does not solve the issue, it definitely minimizes the redundant code to just the bind call and most importantly gives me a variadic parameter based delegate system I can use everywhere.
Usage ends us looking like this..
Maybe you should explain what you want to do in a little bit more detail. If you're just looking for a solution to handle three different signatures which differ by their parameter types, you could do something like that: