C ++在fold运算符中迭代元组

问题描述 投票:3回答:3

我有一个函数,它接受可变数量的对象,每个对象都有一个可以调用带有某个值的回调的函数。我需要调用该函数并在元组中收集值。由于实际函数异步调用回调这一事实很复杂,因此我无法使用简单的包装器将其转换为传统的返回函数。

只要没有重复的类型,这样的东西就可以了:

template<class T>
class Foo
{
    T T_;
public:
    Foo( T t ) : t_( t ) {}

    template<class Func>
    int callMe( Func func )
    {
        func( t_ );
        return 0; // this is some sort of callback ID
    }
}

template<class... Args>
std::tuple<Args...> collect( Foo<Args>... args )
{
    std::tuple<Args...> result;
    std::vector<int> callbacks
    {
        args.callMe( [&result]( const Args& x )
        {
            std::get<Args>( result ) = x;
        } )...
    };
    return result;
}

// returns tuple<int, double, char>( 1, 2.0, '3' )
auto res = collect( Foo( 1 ), Foo( 2.0 ), Foo( '3' ) );

但是如果我想允许重复类型,我必须以某种方式引入整数序列。有没有办法在没有丑陋的辅助函数的情况下做到这一点?

c++ c++17 variadic-templates
3个回答
4
投票

你可以使用std::apply来“迭代”元组:

template<class... Args>
std::tuple<Args...> collect( Foo<Args>... args )
{
    std::tuple<Args...> result;

    std::apply([&](auto&&... xs)
    {   
        (args.callMe([&](const auto& x)
        {
            xs = x;
        }), ...);
   }, result);

    return result;
}

我无法让编译器同意上面的代码:https://gcc.godbolt.org/z/n53PSd

  • g ++ ICE
  • clang ++报告了一个荒谬的错误

您可以使用lambda表达式在C ++ 20中引入范围内的整数序列:

template<class... Args>
std::tuple<Args...> collect( Foo<Args>... args )
{
    std::tuple<Args...> result;

    [&]<auto... Is>(std::index_sequence<Is...>)
    {
        ( args.callMe( [&result]( const Args& x )
        {
            std::get<Is>( result ) = x;
        } ), ... );
    }(std::make_index_sequence_for<Args...>{});

    return result;
}

1
投票

我不确定这个辅助功能(visit)是否丑陋,至少它看起来不错。

template<class T>
T visit(Foo<T>& t){
    T result;
    t.callMe([&](const T& x){result=x;});
    return result;
}

template<class... Args>
std::tuple<Args...> collect( Foo<Args>... args )
{
    return std::tuple{visit(args)...};
}

1
投票

你可以使用几个lambdas来实现你想要的:

template<class... Args>
std::tuple<Args...> collect( Foo<Args>... args )
{
    return {
        [&args]{
            Args t;
            args.callMe([&t](const Args& x){ t = x; });
            return t;
        }()...
    };
}
© www.soinside.com 2019 - 2024. All rights reserved.