c++ - 可变参数模板索引包扩展

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

假设有以下模板:

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关于索引扩展展示了使用另一个模板使用“索引技巧”,但在我的例子中,我还需要将扩展​​参数传递给 调用 中的函数 em> 方法。这似乎比我想象的要难很多。

我使用 "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), ...)

最佳答案

您可以在那个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

关于c++ - 可变参数模板索引包扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36226555/

相关文章:

c++ - 汇编指令的正则表达式

c++ - 从命名空间基类虚拟继承,具有来自命名空间的私有(private)成员

c++ - 在 C++ 中使用 reinterpret_cast 向下转型

c++ - 模板元编程三元值未达到基本情况

C++线程开销

c++ - vector 元组并向后推

c++ - 为什么函数地址不是常量表达式

c++ - 在 C++ 中寻找比虚拟继承更好的方法

c++ - 错误 : expected template-name before < token

html - TYPO3 整合 HTML