命名空间
变体
操作

std::experimental::apply

来自 cppreference.cn
 
 
实验性
技术规范
文件系统库 (filesystem TS)
库基础 (library fundamentals TS)
库基础 2 (library fundamentals TS v2)
库基础 3 (library fundamentals TS v3)
并行性扩展 (parallelism TS)
并行性扩展 2 (parallelism TS v2)
并发性扩展 (concurrency TS)
并发性扩展 2 (concurrency TS v2)
概念 (concepts TS)
范围 (ranges TS)
反射 (reflection TS)
数学特殊函数 (special functions TR)
实验性非 TS
模式匹配
线性代数
std::execution
契约
2D 图形
 
 
定义于头文件 <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

[编辑] 参见

创建由参数类型定义的类型的 tuple 对象
(函数模板) [编辑]
创建 tuple转发引用
(函数模板) [编辑]