In the current state of c++11 (say gcc 4.7.2), how should I choose between using a variadic-template or a std::initializer_list
when I need a constructor that can take variable arguments?
相关问题
- Sorting 3 numbers without branching [closed]
- How to compile C++ code in GDB?
- Why does const allow implicit conversion of refere
- thread_local variables initialization
- What uses more memory in c++? An 2 ints or 2 funct
相关文章
- Class layout in C++: Why are members sometimes ord
- How to mock methods return object with deleted cop
- Which is the best way to multiply a large and spar
- C++ default constructor does not initialize pointe
- Selecting only the first few characters in a strin
- What exactly do pointers store? (C++)
- Converting glm::lookat matrix to quaternion and ba
- What is the correct way to declare and use a FILE
A variadic template allows you providing arguments of different types, while an
std::initializer_list
is templated with the type of the argument. This means the type of all the elements in the list must be the same (or convertible to the underlying type, but no narrowing conversions are allowed). Depending on whether or not this is desirable for you, you may choose one or the other.Also, a variadic template is usually the default choice if you need perfect forwarding, in that the syntactic form
T&&
can bind to both lvalue references and rvalue references, while a similar type deduction cannot be performed forinitializer_list
:Also notice, that a constructor accepting an
initializer_list
will be invoked by default when you use uniform initialization syntax (i.e. curly braces), even though another viable constructor exists. This may or may not be something you wish to have:I recommend always chosing variadic templates and avoid
std::initializer_list
whenever possible.This is how I would have implemented
std::vector
with C++11:The reason is as showed in
main
, usinginitializer_list
in generic code can lead to different behaviour depending on which type of parentheses was chosen. There is also the possibility to silently change code by adding such an constructor.Another reason are move-only types:
With a variadic template, the number of arguments is known during compilation (and accessible via
sizeof...
). With astd::initializer_list
, the number of arguments is known only at runtime. So part of the decision depends on when you need or want to know how many arguments you have.