Boost绑定占位符参数等于Variadic Template参数的数量

Bli*_*ter 10 c++ templates boost bind variadic-templates

我想知道是否可以在boost :: bind调用中使用传递给可变参数模板的参数数量作为占位符.

像这样的东西:

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
Run Code Online (Sandbox Code Playgroud)

这可能吗?

谢谢

小智 1

肯定有一种部分专业化的方法。你的可变参数不能立即知道参数的数量,对吧?您必须使用编译时递归,在此期间您可以使用 boost::mpl 堆叠您的参数(或使用简单的整数常量增量对它们进行计数)。然后在最后一个非变量递归调用(带有 0 arg)中,您在容器上调用 mpl::size (或者如果您选择这种方式,则仅使用整数计数器)来调用像其他答案一样的 Callable,它包含所有参数,在类型列表的开头加上一个完整的模板参数。这就是你的专长。您为每个参数数量创建一个调用程序,该调用程序将根据其特殊数量的参数调用正确的绑定。(Callable 结构(部分)根据参数整数模板参数的数量进行专门化。即使 Call 函数采用最大数量的参数,它也只包装正确的 boost::bind 调用,例如 bind(.., _1,_2) 对于 Callable<2, T1, T2, T3>) 这并不可怕,但我确认我过去在 C++03 中使用过这种方法。