Function Templates vs. Auto Keyword

前端 未结 3 2065
抹茶落季
抹茶落季 2021-01-31 17:15

Can the auto keyword in C++11 replace function templates and specializations? If yes, what are the advantages of using template functions and specializations over

3条回答
  •  不思量自难忘°
    2021-01-31 17:41

    The only thing which makes it the auto keyword different from template that is you cannot make a generic class using the auto keyword.

    class B { auto a; auto b; }
    

    When you create an object of the above class it will give you an error.

    B b; // Give you an error because compiler cannot decide type so it can not be assigned default value to properties
    

    Whereas using template you can make a generic class like this:

    template  
    
    class B {
        T a;
    };
    
    void main() {
        B b; //No Error
    }
    

提交回复
热议问题