::std::initializer_list vs variadic templates

前端 未结 3 1776
傲寒
傲寒 2021-01-13 03:38

Does passing multiple arguments via ::std::initializer_list offer any advantages over the variadic function template method?

In code:

te         


        
相关标签:
3条回答
  • 2021-01-13 04:25

    You can iterate over an std::initializer_list in a way that you cannot over a parameter pack (unless you have C++17 and you fold it first). So for example you can have for loops with the lists. With parameter packs, you only option to expand them is via recursive specialised definitions.

    0 讨论(0)
  • 2021-01-13 04:26

    On occasions I had used variadic template functions just like yours, but then realized that I needed more parameters, possibly templated. In that case typename... A is too eager, and I was happy to rely on braces on the call site to clearly specify where the variadic list of arguments ends, and where the following optional arguments started.

    0 讨论(0)
  • 2021-01-13 04:32

    There are advantages to having an initializer_list<T> instead of a variadic template, assuming that either one would solve the problem.

    For example, function definitions can only have so many parameters, even variadic ones. Implementations are allowed to have a hard limit, and the standard only requires that limit to be at least 256. The same goes for parameters in a function call.

    By contrast, the number of values in a braced-init-list has a minimum limit of 16K (and implementations will usually permit far more). So if it's reasonable for the user to be calling this function with a gigantic set of values, initializer_list is the only one where you can expect a compiler to work.

    0 讨论(0)
提交回复
热议问题