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?
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With