如何将当前替代类型的 std::variant 传递给可调用对象?

How can I pass the current alternative type of std::variant to a callable?

本文关键字:variant 对象 调用 std 类型      更新时间:2023-10-16

我正在使用运行时确定的参数调用一些用户定义的可调用对象。 我有以下工作:

using argument_t = std::variant< int, bool, double, std::string >;
using argument_list = std::vector< argument_t >;
template < typename Callable, std::size_t... S >
auto invoke_with_args_impl( Callable&& method, const argument_list& args, std::index_sequence< S... > )
{
return std::invoke( method, args[S]... );
}
template < std::size_t size, typename Callable >
auto invoke_with_args_impl( Callable&& method, const argument_list& args )
{
if ( args.size() != size )
{
throw std::runtime_error( "argument count mismatch" );
}
return invoke_with_args_impl( std::forward< Callable >( method ), args, std::make_index_sequence< size >() );
}
template < typename Callable >
auto invoke_with_args( Callable&& method, const argument_list& args )
{
switch ( args.size() )
{
case 0:
return method();
case 1:
return invoke_with_args_impl< 1 >( std::forward< Callable >( method ), args );
//.... ad nauseam

但是,这一切都可以正常工作,argument_t必须是用户定义函数中所有参数的类型才能成功工作。

我正在尝试弄清楚如何传递变体的当前替代类型。

类似的东西

return std::invoke( method, std::get< args[S].index() >( args[S] )... );

但显然这是行不通的...不幸的是,我在这个问题上的技能已经到了尽头。

如何做到这一点?

你可以使用类似的东西:

template<class... Ts> struct overloaded : Ts... { using Ts::operator()...; };
template<class... Ts> overloaded(Ts...) -> overloaded<Ts...>;
template < typename Callable, std::size_t... Is >
auto invoke_with_args_impl(Callable&& method,
const argument_list& args,
std::index_sequence<Is...>)
{
return std::visit(overloaded{
[&](auto&&... ts)
-> decltype(std::invoke(method, static_cast<decltype(ts)>(ts)...))
{ return std::invoke(method, static_cast<decltype(ts)>(ts)...); },
[](auto&&... ts)
-> std::enable_if_t<!std::is_invocable<Callable, decltype(ts)...>::value>
{ throw std::runtime_error("Invalid arguments"); } // fallback
},
args[Is]...);
}

演示