c++ - 使用转换后的 `boost::mpl::vector` s 进行标签调度

标签 c++ visual-c++ template-meta-programming boost-mpl tag-dispatching

我正在尝试使用 boost::mpl::vector 的反向拷贝将标记分派(dispatch)到一个函数中:

using InitOrder = boost::mpl::vector<
    struct Foo,
    struct Bar,
    struct Baz
>;

template <class... Stuff>
void initialize(boost::mpl::vector<Stuff...>) {
    // Initialize in-order
}

template <class... Stuff>
void destroy(boost::mpl::vector<Stuff...>) {
    // Exit in-order
}

void initializeAll() {
    initialize(InitOrder{});
}

void destroyAll() {
    destroy(typename boost::mpl::reverse<InitOrder>::type{});
}

Coliru demo

如您所见,目标是在 initialize 中有两个进程和 destroy可以访问 Stuff盒。然而,正如回答here , boost::mpl::reverse<InitOrder>::type实际上不是 boost::mpl::vector , 调度失败:

main.cpp:27:2: error: no matching function for call to 'destroy'
        destroy(typename boost::mpl::reverse::type{});
        ^~~~~~~
main.cpp:18:6: note: candidate template ignored: could not match 'vector' against 'v_item'
void destroy(boost::mpl::vector) {
     ^
  • 如何轻松地双向操作类型列表?
  • Boost.MPL 是否天生就与可变参数模板不兼容?

如果需要,我可以放弃 Boost.MPL,前提是替代方案是标准的或 Boost。我正在使用 MSVC 14.1。

最佳答案

Is Boost.MPL inherently incompatible with variadic templates?

基本上。 MPL早于 C++11,所以要使用 MPL,您需要使用他们的算法——所以他们的序列概念和他们的迭代器,等等。几乎可以肯定有一个非常简短、聪明的方法来做到这一点,但我只能通过猜测和检查找到那些。


至少,如果您需要做的只是反向操作,这在 C++11 中很容易实现:

template <typename...> struct typelist { };

template <typename TL, typeanme R>
struct reverse_impl;

template <typename T, typename... Ts, typename... Us>
struct reverse_impl<typelist<T, Ts...>, typelist<Us...>>
: reverse_impl<typelist<Ts...>, typelist<Us..., T>>
{ };

template <typename... Us>
struct reverse_impl<typelist<>, typelist<Us...>>
{
    using type = typelist<Us...>;
};

template <typename TL>
using reverse = typename reverse_impl<TL, typelist<>>::type;

因此给定:

using InitOrder = typelist<struct Foo, struct Bar, struct Baz>;

然后 reverse<InitOrder>将是 typelist<struct Baz, struct Bar, struct Foo> ,因此可以按照您想要的方式使用。

关于c++ - 使用转换后的 `boost::mpl::vector` s 进行标签调度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48427712/

相关文章:

c++ - 模板尾部结构凸起 "incomplete type in nested name specifier"

c++ - 动力溢出

c++ - 我可以通过编程推断出 C++ dll 使用的调用约定吗?

c++ - 使用VS2010在Windows Server 2008平台远程调试C++;缺少 MSVCP100D.dll

c++ - 如何使用 char* 调用带有 string& 参数的方法?

C++ COM+ 方法参数推导

c++ - 继承问题 : Using pointers with class instantiation not working as expected

c++ - 如何获取捕获的着色器参数的值

c++ - 可以使用ofstream在打印机上打印

c++ - 模板和类型名称语法