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

Lambda表达式下划线问题:Boost::DI框架代码解析咨询

What's That Underscore (_) Doing in the Boost::DI Constructor Size Function?

Great question—let's unpack this step by step, since this is a clever (but slightly tricky) C++11-era trick.

First, let's recap what this function is trying to do: it's figuring out the largest number of arguments (from the sequence Ns...) that type T can be constructed with (specifically, constructing T using a sequence of Ns integral constant parameters, based on the std::make_index_sequence<Ns> check).

Now, onto the underscore:

  • The line int _[]{(is_constructible<T, std::make_index_sequence<Ns>>{}? value = Ns : value)...}; creates an unnamed local array—we use _ as its name because we don't actually need to refer to it later.
  • Back in C11, before fold expressions were introduced in C17, this was a go-to workaround to force the compiler to evaluate every expression in a parameter pack. The array's initializer list expands the (condition ? value = Ns : value) expression for every Ns in the pack.
  • Each time the expression runs, if T can be constructed with Ns arguments (per the is_constructible trait), we update value to that Ns. By the time the array finishes initializing, value holds the largest valid argument count from the sequence.

The underscore is just a throwaway variable name—it's a widely used convention in C++ for variables we don't intend to use. The array itself doesn't serve any purpose beyond triggering the evaluation of all those pack expressions. We don't read from it, we don't pass it around—we just need the compiler to run each step in the pack to update value.

A quick side note: while _ is a common choice here, you might see other names like unused in similar code. In this local scope, it's totally safe—no conflicts with reserved names to worry about.


内容的提问来源于stack exchange,提问作者Anton Quelle

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:24:41