Lambda表达式下划线问题:Boost::DI框架代码解析咨询
_) 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 everyNsin the pack. - Each time the expression runs, if
Tcan be constructed withNsarguments (per theis_constructibletrait), we updatevalueto thatNs. By the time the array finishes initializing,valueholds 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

