我们可以使用可变参数模板函数过滤特定类型的参数,然后将其余参数传递给另一个函数吗? [英] Can we use variadic template function to filter parameters of specific type, then pass the rest to another function?
本文介绍了我们可以使用可变参数模板函数过滤特定类型的参数,然后将其余参数传递给另一个函数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如
// we have a variadic function
void print(...);
// I need such a function to filter parameters of specific type
template<typename... Args>
void print_filter(const Args&... args)
{
// filter non-integral type
print(integral args);
}
// my goal, all non-integral type can be ignored:
print_filter(1.0, 2, "abc", 3) == print(2, 3)
我已经用尽我的知识来做到这一点...您能帮忙吗?或只是证明这是不可能的,这也非常有帮助.谢谢
I have used up my knowledge to do that... can you help? or just to prove it's impossible, which also be very helpful. Thanks
推荐答案
一个巧妙的技巧是将所需的参数转换为1元素转发元组,将不需要的参数转换为空元组,tuple_cat
结果,然后将结果元组 apply
(C ++ 17)应用于要调用的函数:
A neat trick is to convert the arguments you want into a 1-element forwarding tuple, the arguments you don't want into an empty tuple, tuple_cat
the results, then apply
(C++17) the resulting tuple to the function you want to invoke:
template<typename... Args>
void print_filter(Args&&... args) {
std::apply(
[](auto&&... args) { return print(std::forward<decltype(args)>(args)...); },
std::tuple_cat(
std::get<std::is_integral<typename std::decay<Args>::type>::value ? 0 : 1>(
std::make_tuple(
[](Args&& arg) { return std::tuple<Args&&>{std::forward<Args>(arg)}; },
[](Args&&) { return std::tuple<>{}; }))(
std::forward<Args>(args))...));
}
请注意,这采用了另一个技巧,即使用 get
有条件地将两个函数之一应用于参数.
Note that this employs another trick, which is to use get
to conditionally apply one of two functions to an argument.
这篇关于我们可以使用可变参数模板函数过滤特定类型的参数,然后将其余参数传递给另一个函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文