Why do auto and template type deduction differ for braced initializers?

前端 未结 3 2075
伪装坚强ぢ
伪装坚强ぢ 2020-11-29 09:23

I understand that, given a braced initializer, auto will deduce a type of std::initializer_list, while template type deduction will fail:



        
3条回答
  •  伪装坚强ぢ
    2020-11-29 10:08

    There are two important reasons for templates not to do any deduction (the two that I remember in a discussion with the guy in charge)

    • Concerns about future language extensions (there are multiple meanings you could invent - what about if we wanted to introduce perfect forwarding for braced init list function arguments?)

    • The braces can sometimes validly initialize a function parameter that is dependent

    template
    void assign(T &d, const T& s);
    
    int main() {
      vector v;
      assign(v, { 1, 2, 3 });
    }
    

    If T would be deduced at the right side to initializer_list but at the left side to vector, this would fail to work because of a contradictional argument deduction.

    The deduction for auto to initializer_list is controversial. There exist a proposal for C++-after-14 to remove it (and to ban initialization with { } or {a, b}, and to make {a} deduce to the type of a).

提交回复
热议问题