Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ iterating over tuple in fold operator

I have a function that takes a variable number of objects, each of them has a function that can call a callback with some value. I need to call that function and collect the values in a tuple. It is complicated by the fact that the actual function calls the callback asynchronously, so I can't get away with a simple wrapper that converts it into a traditional returning function.

Something like this works, as long as there are no duplicate types:

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' ) );

But if I want to allow repeated types, I'd have to introduce an integer sequence somehow. Is there a way to do it without ugly helper functions?

like image 822
riv Avatar asked Oct 18 '25 05:10

riv


1 Answers

You can use std::apply to "iterate" over the tuple:

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;
}

I am having trouble getting compilers to agree with the code above, though: https://gcc.godbolt.org/z/n53PSd

  • g++ ICEs

  • clang++ reports a nonsensical error


You can introduce an integer sequence in scope in C++20 using a lambda expression:

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;
}
like image 130
Vittorio Romeo Avatar answered Oct 22 '25 06:10

Vittorio Romeo