C++11-17中auto和decltype

文章目录

      • auto
        • C++11中auto的用法
        • auto的注意点
      • decltype
        • C++11中decltype的用法
        • decltype的注意点
      • C++14和17中的auto和decltype
        • 用auto声明函数返回值
        • auto可用于lambda表达式的参数
        • decltype(auto)声明函数返回类型
        • 用初始化值列表初始化变量auto的语义
        • 在if和switch中用auto
      • 参考资料

  用过matlab、python等语言会发现,刚开始会发现好不舒服。因为变量可以拿起直接就用,根本不需要前面的声明定义,而C++使用一个变量必须要提前声明和定义。这也是动态类(弱类型)和静态类型(强类型)的区别,动态类型类型检查是发生在运行期的,而静态类型是在编译期的。C++当然不可能从强类型转成弱类型(但是C++也支持运行时类型识别RTTI),但是为了方便C++11引入了两个关键字auto和decltype让编译器在编译的时候自动推断出所修饰的变量是什么类型,相当于隐式类型var(C#代码,var i = 10;)

auto

  auto 在C++11之前,是与register 并存。在传统C++ 中,如果一个变量没有声明为register 变量,将自动被视为一个auto 变量。而随着register 被弃用(在C++17 中作为保留关键字,以后使用,目前不具备实际意义),auto现在的意义是类型推导。

C++11中auto的用法
template<typename T, typename U> 
void fun(T a, U b) {
   
	auto c = a + b;
	//...
}

int main() {
   
	auto x = 5;   // x为int
	auto p = new auto(1);  // p为int*
	static auto y = 0.0;   // y为static double
	double fun();    
	auto f = fun(); // f为double
	auto val = 5 / 2.0; // val为double
	vector<int> arr{
    1, 2, 3 };
	for (auto w : arr) {
   }  // w为int
	for (auto it = arr.cbegin(); it != arr.cend(); ++it) {
   }  // it为vector::const_iterator
    
    auto num = strlen("hello");
	cout << sizeof(num) 

你可能感兴趣的:(C/C++)