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

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

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

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]...);
}

Demo