::std::initializer_list vs variadic templates

泄露秘密 提交于 2019-12-07 12:29:02

问题


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

In code:

template <typename T> void f(::std::initializer_list<T> const);

template <typename ...A> void f(A&& ...args);

Note that the types A... can be restricted to a single type as well, through SFINAE or static_assert(). The arguments can be iterated through ...


回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/37139379/stdinitializer-list-vs-variadic-templates

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!