c++ - 制作可变参数函数,它接受任意仿函数并返回输入仿函数的每个返回值的元组

标签 c++ c++11 tuples variadic-templates

我想制作一个函数对象,它接受任意函数对象并返回一个元组,该元组存储每个函数对象的返回值。

为了实现这个目标,我做了一个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...);
    }
};

在 main 函数中,我创建了三个 lambda。

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 编译。但是,它并不像我预期的那样工作。 我该如何修改这段代码?

最佳答案

我认为问题在于您缺少 return 语句:

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 段:

[...] 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.

关于c++ - 制作可变参数函数,它接受任意仿函数并返回输入仿函数的每个返回值的元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15059250/

相关文章:

c++ - IP 网络中的动态松散源路由

c++ - 数组元素到可变参数模板参数

c++ - 使用 constexpr 初始化数组?

c# - 列出超过 8 个项目的元组

arrays - 如何将数组转换为元组?

c++ - OpenGL 无效的纹理或状态

C++ typedef 和返回类型 : how to get the compiler to recognize the return type created with typedef?

python - 当列表中的元组没有返回任何内容时写入错误

c++ - condition_variable 项不计算为采用 0 个参数的函数

c++ - 没有可行的重载运算符来引用 map