Why is the std::initializer_list constructor preferred when using a braced initializer list?

前端 未结 3 1740
借酒劲吻你
借酒劲吻你 2020-12-01 07:50

Consider the code

#include 

class Foo
{
    int val_;
public:
    Foo(std::initializer_list il)
    {
        std::cout <<          


        
3条回答
  •  猫巷女王i
    2020-12-01 08:12

    §13.3.1.7 [over.match.list]/p1:

    When objects of non-aggregate class type T are list-initialized (8.5.4), overload resolution selects the constructor in two phases:

    • Initially, the candidate functions are the initializer-list constructors (8.5.4) of the class T and the argument list consists of the initializer list as a single argument.
    • If no viable initializer-list constructor is found, overload resolution is performed again, where the candidate functions are all the constructors of the class T and the argument list consists of the elements of the initializer list.

    If the initializer list has no elements and T has a default constructor, the first phase is omitted. In copy-list-initialization, if an explicit constructor is chosen, the initialization is ill-formed.

    As long as there is a viable initializer-list constructor, it will trump all non-initializer-list constructors when list-initialization is used and the initializer list has at least one element.

提交回复
热议问题