std::experimental::apply
来自 cppreference.cn
< cpp | experimental
定义于头文件 <experimental/tuple> |
||
template< class F, class Tuple > constexpr decltype(auto) apply(F&& f, Tuple&& t); |
(library fundamentals TS) | |
调用 Callable 对象 f,使用参数元组。
目录 |
[编辑] 参数
f | - | Callable 对象,要调用 |
t | - | 元组,其元素将用作 f 的参数 |
[编辑] 返回值
由 f 返回的内容。
[编辑] 可能的实现
namespace detail { template<class F, class Tuple, std::size_t... I> constexpr decltype(auto) apply_impl(F&& f, Tuple&& t, std::index_sequence<I...>) { return std::invoke(std::forward<F>(f), std::get<I>(std::forward<Tuple>(t))...); // Note: std::invoke is a C++17 feature } } // namespace detail template<class F, class Tuple> constexpr decltype(auto) apply(F&& f, Tuple&& t) { return detail::apply_impl(std::forward<F>(f), std::forward<Tuple>(t), std::make_index_sequence<std::tuple_size_v<std::decay_t<Tuple>>>{}); } |
[编辑] 示例
运行此代码
#include <iostream> #include <tuple> template<typename... Ts> void print_tuple(const std::tuple<Ts...> &tuple) { std::apply([](const auto&... elem) { ((std::cout << elem << '\n'), ...); }, tuple); } int main() { const std::tuple<int, char> t = std::make_tuple(5, 'a'); print_tuple(t); }
输出
5 a
[编辑] 参见
(C++11) |
创建由参数类型定义的类型的 tuple 对象(函数模板) |
(C++11) |
创建 tuple 的转发引用(函数模板) |