You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

std::apply是否仅可作用于std::tuple?非tuple对象调用是否合法?

std::apply支持非std::tuple参数属于合法行为,不属于未定义行为

你看到的标准章节的标题只是该功能所属模块的分类标识:

20.5.5 使用参数**tuple**调用函数
这里的tuple是泛指类tuple类型,不是对入参的强制约束,不要求必须是std::tuple的特化。

查阅C++标准中std::apply的具体规范可以发现,它对输入参数的要求是满足*tuple-like(类tuple)*类型的约束,即:

  • 该类型存在std::tuple_size_v的有效特化
  • 可以通过std::get<N>(实例)获取对应索引位置的元素

而C++标准库已经默认给std::array、std::pair提供了符合要求的std::tuple_size特化和std::get重载,所以它们都是合法的入参类型,传给std::apply完全符合标准要求,不会触发未定义行为。
示例代码:

#include <tuple>
#include <utility>
#include <array>

int main() {
  std::apply([](int, int) {}, std::array{0, 0});
  std::apply([](int, int) {}, std::pair {0, 0});
  std::apply([](int, int) {}, std::tuple{0, 0});
}

实际上tuple-like是C++标准里明确规定的通用概念,设计std::apply的初衷就是支持所有符合该概念的类型,而非仅限于std::tuple本身。


内容的提问来源于stack exchange,提问作者康桓瑋

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 07:27:02