Boost.MPL 使用佔位符實現元函數延遲綁定。本文展示如何用 C++11 變參模板、遞歸模板實現極簡版佔位符,並提供宏自動生成任意參數數量的 Lambda 特化。
namespace hi { namespace mpl { namespace placeholders {
namespace helper {
template struct arglist {};
template struct at;
template
struct at> : at> {};
template
struct at<0, arglist> { using type = T; };
}
template struct Arg {
template
struct apply { using type = typename helper::at>::type; };
};
using _1 = Arg<1>; using _2 = Arg<2>; using _3 = Arg<3>; using _4 = Arg<4>;
}}}
template<> struct push_back<_1, _2> {
template
struct apply {
using type = typename push_back<
typename _1::apply::type,
typename _2::apply::type
>::type;
};
};
為支援參數順序任意組合(如 `push_back<_2, _1>`),需生成 n! 個特化。文中給出 `SUPPORT_LAMBDA(classname, n, prefix)` 宏,可一鍵生成 n=1~5 的全排列特化代碼,避免手寫繁瑣模板。