[英]Using an index in variadic function template
template <std::size_t N, class... Args>
using type = typename std::tuple_element<N, std::tuple<Args...>>::type;
template<typename ...Args, typename Func>
typename std::result_of<Func(Args...)>::type functionOnParams(Func fp, Args&&...args)
{
using Indices = std::make_index_sequence<sizeof...(Args)>;
int ints[2] = {1,2};
return fp(std::forward<Args>( static_cast<type<index_of_args, Args...>>(ints[index_of_args++]) )...);
}
Hi, I have spent a number of hours trying to figure to how to get the index_of_args for the above code.嗨,我花了几个小时试图弄清楚如何获取上述代码的 index_of_args。 Any help would be appreciated.
任何帮助,将不胜感激。 My searches keep going around in circles.
我的搜索一直在兜圈子。 index_of_args does not exist.
index_of_args 不存在。 I need to generate this index for each element of the std::forward.
我需要为 std::forward 的每个元素生成这个索引。 Thank you
谢谢
you can get make an std::index_sequence
from Args
and pass them to a helper function (by template arguments deduction ).您可以从
Args
中获取一个std::index_sequence
并将它们传递给助手 function(通过模板 arguments 推导)。 and then do anything you want in the helper function.然后在助手 function 中做任何你想做的事。
template<typename Func, typename... Args, size_t... Is, typename RealArgs>
std::invoke_result_t<Func&&, Args&&...> helper(Func&& func, std::index_sequence<Is...>* indicesTag, std::tuple<Args...>* argsTypeTag, RealArgs&& args){
return std::forward<Func>(func)(std::forward<Args>(std::forward<RealArgs>(args)[Is])...);
}
template<typename Func, typename... Args>
std::invoke_result_t<Func&&, Args&&...> functionOnParams(Func&& func, Args&&... args){
int a[] = { 0, 1 };
return helper(std::forward<Func>(func), (std::index_sequence_for<Args...>*)nullptr, (std::tuple<Args...>*)nullptr, a /* anything to replace the arguments */);
}
int main(){
auto x = functionOnParams(std::plus<>(), 0, 1.0f);
std::cout << x;
return 0;
}
in the other hand, you can also use class template specialization to pass the std::index_sequence
and Args
.另一方面,您也可以使用class 模板特化来传递
std::index_sequence
和Args
。
template<typename, typename>
struct Helper;
template<typename... Args, size_t... Is>
struct Helper<std::index_sequence<Is...>, std::tuple<Args...>>{
template<typename Func, typename RealArgs>
static std::invoke_result_t<Func&&, Args&&...> call(Func&& func, RealArgs&& args){
return std::forward<Func>(func)(std::forward<Args>(std::forward<RealArgs>(args)[Is])...);
}
};
template<typename Func, typename... Args>
std::invoke_result_t<Func&&, Args&&...> functionOnParams(Func&& func, Args&&... args){
int a[] = { 0, 1 };
return Helper<std::index_sequence_for<Args...>, std::tuple<Args...>>::call(std::forward<Func>(func), a /* anything to replace the arguments */);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.