我不知道这个模式的名称,即使它存在.我需要一个函数来返回一组将在另一个函数中使用的参数.例如,我有这个功能:
void foo(int a, float b, some_class c);
Run Code Online (Sandbox Code Playgroud)
我想写一个这样的函数:
//Theoretical code:
arguments get_arguments(){
return arguments(0,0.0f, some_class());
}
Run Code Online (Sandbox Code Playgroud)
然后foo像这样打电话:
foo(get_arguments());
Run Code Online (Sandbox Code Playgroud)
这可能吗?如果有,怎么样?
如果您的编译器支持将来的C++ 17添加,您可以通过修改get_arguments()为return std::tuple并使用来完成此操作std::apply:
std::apply(foo, get_arguments())
Run Code Online (Sandbox Code Playgroud)
get_arguments可以实现std::make_tuple:
auto get_arguments(){
return std::make_tuple(0,0.0f, some_class());
}
Run Code Online (Sandbox Code Playgroud)
这将返回一个std::tuple<int,float,some_class>.
您可以foo使用std::experimental::applyC++ 17中的参数调用:
std::experimental::apply(foo, get_arguments());
Run Code Online (Sandbox Code Playgroud)
如果您需要,可以std::experimental::apply 在这里实施.
要清理呼叫,您可以添加转发功能:
template <typename Tuple>
void foo(Tuple&& t) {
return std::experimental::apply(
static_cast<void(*)(int,float,some_class)>(&foo),
std::forward<Tuple>(t));
}
Run Code Online (Sandbox Code Playgroud)
然后你可以使用你想要的语法:
foo(get_arguments());
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
218 次 |
| 最近记录: |