使可变函数接受任意函子并返回输入函子的每个返回值的元组 [英] Make variadic function which takes arbitary functors and returns a tuple of each return value of input functors
问题描述
我想创建一个函数对象,它接受任意函数对象,并返回一个元组,它存储每个函数对象的返回值。
I want to make a function object which takes arbitrary function objects and returns a tuple which stores the return value of each function object.
为了达到这个目标,我做了一个 A类
To achieve this goal, I made a class A
class A
{
private:
template <class Ret, class Func>
auto impl(Ret ret, Func func) -> decltype(tuple_cat(ret, make_tuple(func())))
{
return tuple_cat(ret, make_tuple(func()));
}
template <class Ret, class First, class... Funcs>
auto impl(Ret ret, First first, Funcs... funcs)
-> decltype(impl(tuple_cat(ret, make_tuple(first())), funcs...))
{
return impl(tuple_cat(ret, make_tuple(first())), funcs...);
}
public:
template <class Func>
auto operator()(Func func) -> decltype(make_tuple(func()))
{
return make_tuple(func());
}
template <class First, class... Funcs>
auto operator()(First first, Funcs... funcs)
-> decltype(impl(make_tuple(first()),funcs...))
{
impl(make_tuple(first()),funcs...);
}
};
在主要功能中,我做了三个羔羊。
And in the main function, I made three lambdas.
int main(){
auto func1 = [](){ cout << 1 << endl; return 1;};
auto func2 = [](){ cout << 2 << endl; return 2;};
auto func3 = [](){ cout << 3 << endl; return 3;};
A a;
auto x = a(func1, func2);
cout << "ans : " << get<0>(x) << get<1>(x) << endl; // I expect ans : 12
}
这段代码可以通过gcc 4.7编译。 2。但是,它不工作,因为我的预期。
我应该如何修改此代码?
This code can be compiled by gcc 4.7.2. However, it doesn't work as I expected. How should I modify this code?
推荐答案
我认为问题是你缺少一个 return
语句:
I think the problem is that you're missing a return
statement:
template <class First, class... Funcs>
auto operator()(First first, Funcs... funcs)
-> decltype(impl(make_tuple(first()),funcs...))
{
return impl(make_tuple(first()),funcs...);
// ^^^^^^
}
代码具有未定义的行为。根据C ++ 11标准的第6.6.3 / 2节:
Without it, your code has Undefined Behavior. Per Paragraph 6.6.3/2 of the C++11 Standard:
[...]相当于没有价值的回报;这会导致价值回报函数中的未定义行为。
[...] Flowing off the end of a function is equivalent to a return with no value; this results in undefined behavior in a value-returning function.
这篇关于使可变函数接受任意函子并返回输入函子的每个返回值的元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!