C将同类包装类型的元组转换为原始类型的元组
作者:互联网
我想将std :: apply()调用到函数中;但是,我无法,因为我使用的std :: tuple目前已被包装.例如:
#include <tuple>
template <class T>
struct wrapped
{
wrapped(T t) : t(t) {}
T t;
};
template <class T, class ... Args>
struct delay_call
{
T(*callback)(Args...);
std::tuple<Args...> params;
delay_call(T(*callback)(Args...), Args ... params) :
callback(callback), params(params...)
{}
T call()
{
return std::apply(callback, params);
}
};
template <class T, class ... Args>
struct delay_call_with_wrap
{
T(*callback)(Args...);
std::tuple<wrapped<Args>...> w_params;
delay_call_with_wrap(T(*callback)(Args...), wrapped<Args> ... w_params) :
callback(callback), w_params(w_params...)
{}
T call()
{
std::tuple<Args...> params; // = w_params.t
return std::apply(callback, actual_params);
}
};
float saxpy(float a, float x, float y)
{
return a * x + y;
}
int main()
{
float a = 1, x = 2, y = 3;
delay_call delay_saxpy(saxpy, a, x, y);
wrapped w_a = 1.f, w_x = 2.f, w_y = 3.f;
delay_call_with_wrap w_delay_saxpy(saxpy, w_a, w_x, w_y);
float result = delay_saxpy.call();
float w_result = w_delay_saxpy.call();
}
delay_call结构按预期工作;但是,我不确定如何提取每个元组元素的实际值并将其赋予std :: apply()来执行.
简而言之,对于delay_call_with_wrap :: call,我将如何转换std :: tuple< wrapped< Args> …>到std :: tuple< Args ...>?
解决方法:
我会完全避免使用std :: apply并通过使用std :: index_sequence解压缩元组来直接调用回调:
template <std::size_t ...I> T call_low(std::index_sequence<I...>)
{
return callback(std::get<I>(w_params).t...);
}
T call()
{
return call_low(std::make_index_sequence<sizeof...(Args)>{});
}
标签:c,wrapper,variadic-templates,c17,stdtuple 来源: https://codeday.me/bug/20190727/1548899.html