您不需要在这里使用宏。看它住在 Coliru 上:
#include <boost/fusion/adapted/std_tuple.hpp>
#include <boost/fusion/algorithm.hpp>
#include <boost/phoenix.hpp>
template <typename... F>
struct sequence_application
{
explicit sequence_application(F... fs) : fs(fs...) { }
template <typename... Args>
void operator()(Args const&... args) const {
namespace phx = boost::phoenix;
using namespace phx::arg_names;
boost::fusion::for_each(fs, phx::bind(arg1, phx::cref(args)...));
}
private:
std::tuple<F...> fs;
};
template <typename... F>
sequence_application<F...> apply_all(F&&... fs) {
return sequence_application<F...>(std::forward<F>(fs)...);
}
让我们演示一下:
#include <iostream>
#include <string>
void foo(const char* v) { std::cout << __FUNCTION__ << ": " << v << "\n"; }
void bar(std::string v) { std::cout << __FUNCTION__ << ": " << v << "\n"; }
struct poly_functor {
template <typename... T>
void operator()(T&...) const { std::cout << __PRETTY_FUNCTION__ << "\n"; }
};
您当然可以像问题中那样进行直接调用:
poly_functor pf;
apply_all(&foo, &bar, pf)("fixed invocation is boring");
但是,这确实相当无聊。怎么样,我们保留复合函子,并将其传递给另一个算法?
auto combined = apply_all(&foo, &bar, pf);
boost::for_each(
std::vector<const char*> {"hello", "world", "from", "various"},
combined);
现在,尝试使用您的宏观方法。宏不是C++ 中的一等语言公民。
最后,让我们展示它与可变参数列表一起使用:
struct /*anonymous*/ { int x, y; } point;
// the variadic case
apply_all(pf)("bye", 3.14, point);
完整的演示打印:
foo: fixed invocation is boring
bar: fixed invocation is boring
void poly_functor::operator()(T &...) const [T = <char const[27]>]
foo: hello
bar: hello
void poly_functor::operator()(T &...) const [T = <const char *const>]
foo: world
bar: world
void poly_functor::operator()(T &...) const [T = <const char *const>]
foo: from
bar: from
void poly_functor::operator()(T &...) const [T = <const char *const>]
foo: various
bar: various
void poly_functor::operator()(T &...) const [T = <const char *const>]
void poly_functor::operator()(T &...) const [T = <char const[4], const double, const <anonymous struct at test.cpp:54:5>>]