如何将当前替代类型的 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]...);
}
演示
相关文章:
- 什么时候调用组成单元对象的析构函数
- 对RValue对象调用的LValue ref限定成员函数
- CMake-按正确顺序将项目与C运行时对象文件链接
- 空基优化子对象的地址
- 将对象数组的引用传递给函数
- 你能重载对象变量名本身返回的内容吗
- C++使用整数的压缩数组初始化对象
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 将对象移动到std::shared_ptr
- 代理对象的常量正确性
- 提升 ASIO 无法识别计时器对象
- 将Ref对象作为类成员
- 更改其类型后,丢失对 std::variant 对象的引用
- 将 std::variant 与 gmock 1.8 对象一起使用时编译错误
- 如何访问从 COM 对象返回的 VARIANT 数据类型中的安全数组C++?
- 如何将当前替代类型的 std::variant 传递给可调用对象?
- 如何构造一个 std::variant 类型对象,其自身 Templated 和构造函数转发参数
- 为什么 std::variant 不能容纳数组对象类型,而联合可以?
- 在 boost::variant 对象的向量后进行清理
- 将代码从 vb6 转换为 c#-System.Variant.Marshal Helper 将对象转换为变体'