RnM*_*Mss 3 c++ variadic-templates
是否存在现有的函数(或语法),例如:
inline void noop(...) { /* EMPTY */ }
Run Code Online (Sandbox Code Playgroud)
所以我可以做这样的事情:
template <class... T>
void foo(T... args) {
noop( do_side_effect<T>(args)... );
}
Run Code Online (Sandbox Code Playgroud)
- - - - - - - 编辑 - - - - - -
因为这样的东西不能编译:
template <class... T>
void foo(T... args) {
do_side_effect<T>(args)...;
}
template <class... T>
void foo(T... args) {
( do_side_effect<T>(args)... );
}
Run Code Online (Sandbox Code Playgroud)
------------ 编辑 2 ------------
显示可能用例的示例。
template <class T, class F, int... indices>
void _tuple_foreach_details(T&& tuple, F& functor, std::index_sequence<indices...>){
noop( functor(std::get<indices>(tuple))... );
/* this means:
functor(std::get<0>(tuple));
functor(std::get<1>(tuple));
...
functor(std::get<N>(tuple));
*/
}
template <class T, class F>
void tuple_foreach(T&& tuple, F& functor) {
_tuple_foreach_details<T, F, std::make_index_sequence<std::tuple_size_v<T>>>(tuple, functor, {});
}
Run Code Online (Sandbox Code Playgroud)
不,没有这样的标准功能。我们需要确保包中的任何表达式都没有void类型。而且由于函数参数的求值相对于彼此是不确定的,用例变得更加小众,因为没有办法强制执行顺序,而表达式的有序应用程序就足够了,即使我们不关心命令。
所以使用 C++17,我会用折叠表达式来做,如下所示
( (do_side_effect<T>(args), void()), ... );
Run Code Online (Sandbox Code Playgroud)
, void()是为了确保包中每个项目的类型不会干扰逗号上的折叠(因为operator,是可重载的)。然后用逗号运算符扩展该表达式,。你自己差点就到了那里,但它失败了,因为你省略了逗号运算符。
| 归档时间: |
|
| 查看次数: |
66 次 |
| 最近记录: |