auto 的一个应用就是当我们不知道变量是什么类型,或者不希望指明具体类型的时候,比如泛型编程中。我们看例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
   | #include <iostream> using namespace std;
  class A{ public:     static int get(void){         return 100;     } };
  class B{ public:     static const char* get(void){         return "http://c.biancheng.net/cplus/";     } };
  template <typename T> void func(void){     auto val = T::get();      cout << val << endl; }
  int main(void){     func<A>();     func<B>();
      return 0; }
   | 
 
运行结果:
1 2
   | 100 http://c.biancheng.net/cplus/
   | 
 
本例中的模板函数 func() 会调用所有类的静态函数 get(),并对它的返回值做统一处理,但是 get() 的返回值类型并不一样,而且不能自动转换。这种要求在以前的 C++ 版本中实现起来非常的麻烦,需要额外增加一个模板参数,并在调用时手动给该模板参数赋值,用以指明变量 val 的类型。
但是有了 auto 类型自动推导,编译器就根据 get() 的返回值自己推导出 val 变量的类型,就不用再增加一个模板参数了。
下面的代码演示了不使用 auto 的解决办法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
   | #include <iostream> using namespace std;
  class A{ public:     static int get(void){         return 100;     } };
  class B{ public:     static const char* get(void){         return "http://c.biancheng.net/cplus/";     } };
  template <typename T1, typename T2>   void func(void){     T2 val = T1::get();     cout << val << endl; }
  int main(void){          func<A, int>();     func<B, const char*>();
      return 0; }
   |