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

前端 未结 3 2069
伪装坚强ぢ
伪装坚强ぢ 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:05

    First of all it's "speculative explanations of the form "this could be the reason"" as you call it.

    {1,2,3} is not only std::initializer_list but also allow initialize types without constructor. For example:

    #include 
    
    struct x{
        int a,b,c;
    };
    
    void f(x){
    
    }
    int main() {
        f({1,2,3});
    }
    

    is correct code. To show that it isn't initializer_list let's see the following code:

    #include 
    
    struct x{int a,b,c;};
    
    void f(x){
    
    }
    int main() {
        auto il = {1, 2, 3};
        f(il);
    }
    

    Error is:

    prog.cpp: In function ‘int main()’:
    prog.cpp:10:9: error: could not convert ‘il’ from ‘std::initializer_list’ to ‘x’
    

    And now to the question "What is the difference?"

    in auto x = {1, 2, 3}; code it's OK to determine type, because coder explicitly said "It's not important what's type it is" using auto

    While in case of function template he may be sure that he is using different type. And it's good to prevent errors in ambiguous cases (It doesn't seem like C++ style , through).

    Especially bad it will be in case when there was 1 function f(x) and then it was changed to template one. Programmer wrote to use it as x, and after adding new function for other type it slightly change to call completely different one.

提交回复
热议问题