【问题标题】:Variadic template indexed pack expansion可变参数模板索引包扩展
【发布时间】:2016-03-26 17:35:50
【问题描述】:

假设以下模板:

template<typename T, bool stack>
struct bind_argument
{
    static inline T get_arg(Object& obj, u8 index)
    {
        return ...;
    }
};

template<typename RT, typename Arg0, typename... Args>
inline RT call(Object& obj, RT(*function)(Arg0, Args...))
{
    constexpr bool use_stack = ...;
    return function(..., bind_argument<Args, use_stack>::get_arg(obj, 0)...);
}

对于 bind_argument 我需要传递扩展的索引。 Another question 关于索引扩展展示了使用另一个模板使用“索引技巧”,但在我的情况下,我还需要将扩展​​参数传递给 中的 函数 的调用调用方法。这似乎比我想象的要难。

我使用"indices trick" 的原始解决方案如下所示:

template<bool stack, typename... Args, u64... Indices>
struct bind_arguments
{
    static inline Args get_args(CPU& cpu, indices<Indices...>)
    {
        return bind_argument<Args, stack>(cpu, Indices)...;
    }
};

template<typename RT, typename Arg0, typename... Args>
inline RT call(Object& obj, RT(*function)(Arg0, Args...))
{
    constexpr bool use_stack = ...;
    Arg0 some_value = ...;
    return function(some_value, bind_arguments<use_stack, Args...>::get_args(obj, build_indices<sizeof...(Args)>{}));
}

不幸的是,这不会编译。如何在另一个模板中执行模板索引包扩展,然后将扩展值传递到用于扩展值的位置? (在本例中为 function() 调用)

预期的调用扩展如下:

function(some_value, bind_argument<A1, use_stack>(obj, 0), bind_argument<A2, use_stack>(obj, 1), bind_argument<A3, use_stack>(obj, 2), ...)

【问题讨论】:

  • 我不明白这个问题。您能否举例说明扩展后的调用应该是什么样子(例如,call&lt;O, A0, A1, A2&gt; 会扩展成什么?)
  • @T.C.你从我嘴里说出来的话。我认为他想构建一个包含 (arg, index) 元组的对象...在我看来,这听起来像是 tuple()std::forward_as_tuple()
  • 我添加了一个非最终扩展的示例。该用法适用于需要使用各种参数调用 HLE 函数的仿真器(第一个参数始终相同,因此 Arg0)。 bind_argument 从寄存器(或堆栈)中获取参数并将它们转换为正确的类型。这个问题在某种程度上是我previous question 的延续。
  • 或许this
  • @PiotrSkotnicki 这正是我所需要的!你或许应该回答一下,这样我才能接受。

标签: c++ templates c++11 variadic-templates


【解决方案1】:

你可以在那个other函数中做任何你想做的事,转发所有必要的参数;除了最终结果,没有理由返回任何内容:

#include <utility>
#include <cstddef>

template <typename RT, typename Arg0, typename... Args, std::size_t... Is>
inline RT call(Object& obj, RT(*function)(Arg0, Args...), std::index_sequence<Is...>)
{
    return function(&obj, bind_argument<Args>::get_arg(obj, Is)...);
}

template <typename RT, typename Arg0, typename... Args>
inline RT call(Object& obj, RT(*function)(Arg0, Args...))
{
    return call(obj, function, std::make_index_sequence<sizeof...(Args)>{});
}

DEMO

【讨论】:

    猜你喜欢
    • 2014-10-30
    • 1970-01-01
    • 2015-05-21
    • 2014-04-12
    • 2013-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多