Search code examples
c++templatesauto

What is the difference between auto deduction and template type deduction?


Let we have the following code

    auto x = { 11, 23, 9 }; 
    template<typename T> // template with parameter
    void f(T param); 

    f({ 11, 23, 9 }); // error! can't deduce type for T

Here in the following code auto is deduced automatically while template is not deduced automatically.

  • How auto type is deduced?

  • what is auto type behind the scenes?


Solution

  • auto type deduction is usually the same as template type deduction, but auto type deduction assumes that a braced initializer represents a std::initializer_list, and template type deduction doesn’t.

    When an auto–declared variable is initialized with a braced initializer, the deduced type is an instantiation of std::initializer_list. But if the corresponding template is passed the same initializer, type deduction fails, and the code is rejected:

    auto x = { 11, 23, 9 }; // x's type is     
                           //std::initializer_list<int>
    template<typename T> // template with parameter
    void f(T param); // template with parameter
    

    However, if you specify in the template that param is a std::initializer_list<T> for some unknown T, template type deduction will deduce what T is:

    template<typename T>
    void f(std::initializer_list<T> initList);
    f({ 11, 23, 9 }); // T deduced as int, and initList's
     // type is std::initializer_list<int>
    

    Remember

    • auto type deduction is usually the same as template type deduction, but auto type deduction assumes that a braced initializer represents a std::initializer_list, and template type deduction doesn’t.