📜  C++中的类型推断(自动和DECLTYPE)

📅  最后修改于: 2021-05-26 03:04:55             🧑  作者: Mango

类型推断是指以编程语言自动推导出表达式的数据类型。在C++ 11之前,需要在编译时显式声明每种数据类型,从而在运行时限制表达式的值,但是在新版本的C++之后,包含了许多关键字,这些关键字使程序员可以将类型推导留给编译器本身。
有了类型推断功能,我们可以花更少的时间写出编译器已经知道的东西。由于仅在编译器阶段推导所有类型,因此编译时间会稍微增加,但不会影响程序的运行时间。

自动关键字

auto关键字指定将要从其初始值设定项中自动推断出要声明的变量的类型。对于函数,如果它们的返回类型是auto,那么它将在运行时由返回类型expression求值。

使用auto关键字声明的变量仅应在声明时进行初始化,否则会出现编译时错误

CPP
// C++ program to demonstrate working of auto
// and type inference
#include 
using namespace std;
  
int main()
{
    // auto a; this line will give error
    // because 'a' is not initialized at
    // the time of declaration
    // a=33;
  
    // see here x ,y,ptr are
    // initialised at the time of
    // declaration hence there is
    // no error in them
    auto x = 4;
    auto y = 3.37;
    auto ptr = &x;
    cout << typeid(x).name() << endl
         << typeid(y).name() << endl
         << typeid(ptr).name() << endl;
  
    return 0;
}


C++
// C++ program to demonstrate that we can use auto to
// save time when creating iterators
#include 
using namespace std;
  
int main()
{
    // Create a set of strings
    set st;
    st.insert({ "geeks", "for", 
               "geeks", "org" });
  
    // 'it' evaluates to iterator to set of string
    // type automatically
    for (auto it = st.begin(); 
         it != st.end(); it++)
        cout << *it << " ";
  
    return 0;
}


CPP
// C++ program to demonstrate use of decltype
#include 
using namespace std;
  
int fun1() { return 10; }
char fun2() { return 'g'; }
  
int main()
{
    // Data type of x is same as return type of fun1()
    // and type of y is same as return type of fun2()
    decltype(fun1()) x;
    decltype(fun2()) y;
  
    cout << typeid(x).name() << endl;
    cout << typeid(y).name() << endl;
  
    return 0;
}


CPP
// Another C++ program to demonstrate use of decltype
#include 
using namespace std;
int main()
{
    int x = 5;
  
    // j will be of type int : data type of x
    decltype(x) j = x + 5;
  
    cout << typeid(j).name();
  
    return 0;
}


CPP
// C++ program to demonstrate use of decltype in functions
#include 
using namespace std;
  
// A generic function which finds minimum of two values
// return type is type of variable which is minimum
template 
auto findMin(A a, B b) -> decltype(a < b ? a : b)
{
    return (a < b) ? a : b;
}
  
// driver function to test various inference
int main()
{
    // This call returns 3.44 of doubale type
    cout << findMin(4, 3.44) << endl;
  
    // This call returns 3 of double type
    cout << findMin(5.4, 3) << endl;
  
    return 0;
}


输出
i
d
Pi

我们使用typeid来获取变量的类型。 typeid是一个运算符,用于需要知道对象的动态类型的地方。 typeid(x).name()返回x数据类型的简写名称,例如,它返回i代表整数,d代表双精度,Pi代表整数指针等。但是返回的实际名称主要取决于编译器。您可以在此处阅读有关typeid的更多信息。 auto的一个好用法是在为容器创建迭代器时避免长时间的初始化。

C++

// C++ program to demonstrate that we can use auto to
// save time when creating iterators
#include 
using namespace std;
  
int main()
{
    // Create a set of strings
    set st;
    st.insert({ "geeks", "for", 
               "geeks", "org" });
  
    // 'it' evaluates to iterator to set of string
    // type automatically
    for (auto it = st.begin(); 
         it != st.end(); it++)
        cout << *it << " ";
  
    return 0;
}
输出
for geeks org 

注意:即使将整数引用分配给auto,auto也会变成int类型。为了使其成为参考类型,我们使用了自动&。

// function that returns a 'reference to int' type
int& fun() {   }

// m will default to int type instead of
// int& type
auto m = fun();

// n will be of int& type because of use of
// extra & with auto keyword
auto& n = fun();

decltype关键字

它检查实体的声明类型或表达式的类型。 Auto使您可以声明具有特定类型的变量,而decltype则允许您从变量中提取类型,因此decltype是一种运算符,用于评估所传递表达式的类型。
上述关键字及其用法的说明如下:

CPP

// C++ program to demonstrate use of decltype
#include 
using namespace std;
  
int fun1() { return 10; }
char fun2() { return 'g'; }
  
int main()
{
    // Data type of x is same as return type of fun1()
    // and type of y is same as return type of fun2()
    decltype(fun1()) x;
    decltype(fun2()) y;
  
    cout << typeid(x).name() << endl;
    cout << typeid(y).name() << endl;
  
    return 0;
}
输出
i
c

以下是另一个示例来演示decltype的用法

CPP

// Another C++ program to demonstrate use of decltype
#include 
using namespace std;
int main()
{
    int x = 5;
  
    // j will be of type int : data type of x
    decltype(x) j = x + 5;
  
    cout << typeid(j).name();
  
    return 0;
}
输出
i

一个演示同时使用auto和decltype的程序。
下面是一个C++模板函数min_type(),该函数返回至少两个数字。这两个数字可以是任何整数类型。返回类型是使用最少两个的类型确定的。

CPP

// C++ program to demonstrate use of decltype in functions
#include 
using namespace std;
  
// A generic function which finds minimum of two values
// return type is type of variable which is minimum
template 
auto findMin(A a, B b) -> decltype(a < b ? a : b)
{
    return (a < b) ? a : b;
}
  
// driver function to test various inference
int main()
{
    // This call returns 3.44 of doubale type
    cout << findMin(4, 3.44) << endl;
  
    // This call returns 3 of double type
    cout << findMin(5.4, 3) << endl;
  
    return 0;
}
输出
3.44
3


decltype vs typeid:
decltye在编译时给出类型信息,而typeid在运行时给出。因此,如果我们具有引用(或指向)派生类对象的基类引用(或指针),则decltype将给出类型作为基类引用(或指针),而typeid将给出派生类型引用(或指针)。

要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”