使可变函数具有任意数量的void函子 [英] Make variadic function which takes arbitary number of void functors
问题描述
我的动机上一个问题:使变量函数接受任意函数并返回输入函数的每个返回值的元组
现在,我想创建一个类执行可能返回void的每个函数对象。据我所知,我可以做一些像
class A
{
public:
template< class Func>
void operator()(Func func)
{
func();
}
template< class First,class ... Funcs>
void operator()(第一个,Funcs ... funcs)
{
first();
operator()(funcs ...);
}
};
此代码执行作业。
然而,我想必须有更聪明的方式像 Nawaz
和 mfontanini
我试过以下模拟他们的代码。
A
{
public:
template< class ... Func>
void operator()(Func func ...)
{
func()...;
}
};
但是,gcc 4.7.2不能编译。
您可以这样做:
template< class ... Func>
void operator()(Func ... func)//修正这里的语法
{
sink((func(),0)...)
}
其中 sink
定义为:
模板< typename ... T& void sink(T ...){}
sink
是吃表达式(func(),0)
的值,它只是 0
不管 func()
返回什么。即使 func()
返回类型是 void
,它也会工作。
请注意,在上面的演示中,前两个函数返回值,但第三个返回 void
p>
如果你想从左到右调用函数,可以使用list-initialization语法:
int sink [] {func(),0)...}
但它不必要地创建了一个变量。所以我将 sink
定义为struct:
struct sink
{
template< typename ... T>
sink(T ...){} //模板化构造函数!
};
您可以这样做:
sink {(func(),0)...} //现在注意花括号!
更新的演示:
希望有帮助。
Now, I want to make a class which just execute each function object which may return void. To the best of my knowledge, I can make something like,
class A
{
public:
template <class Func>
void operator()(Func func)
{
func();
}
template <class First, class... Funcs>
void operator()(First first, Funcs... funcs)
{
first();
operator()(funcs...);
}
};
This code does the job.
However, I guess there must be much more clever way like the codes by Nawaz
and mfontanini
in the above link.
I tried below imitating their code.
class A
{
public:
template <class... Func>
void operator()(Func func...)
{
func()...;
}
};
However, gcc 4.7.2 doesn't compile. Am I missing here?
You can do this:
template <class... Func>
void operator()(Func ... func) //corrected the syntax here
{
sink( (func(),0)... );
}
where sink
is defined as:
template<typename ...T> void sink(T...) {}
The purpose of sink
is to eat the value of the expression (func(),0)
which is just 0
irrespective of what func()
returns. It will work even if func()
return type is void
.
Notice the in the demo above first two functions return something but the third one returns void
.
If you want the functions to be called from left-to-right, then you can use list-initialization syntax:
int sink[]{func(),0)... };
But it unnecessarily creates a variable. So I would define sink
as struct:
struct sink
{
template<typename ...T>
sink(T...) {} //templated constructor!
};
With this you can do this:
sink { (func(),0)... }; //note the curly-braces now!
Updated demo:
Hope that helps.
这篇关于使可变函数具有任意数量的void函子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!