类型推断

类型推断

auto类型修饰符

在C++11以后,auto关键字能够用于类型推导。当声明语句中有初始化器时,auto能够根据对象的初始化器推断对象的数据类型。

例子:

auto a = 123;		// int
auto b = 123l;		// long
auto c = 3.14;		// double
auto d = 3.14f;		// float
auto e = "Hello";	// const char *
auto f = "Hello"s;	// std::string
auto g = "Hello"sv;	// std::string_view

在编程中适当地使用auto能使程序简化,易读易写。在C++11以前,如果要获得一个容器的迭代器通常要这样写:

std::vector<int> vec;
for (std::vector<int>::const_iterator iter = vec.begin();
        iter != vec.end(); iter++){
            // do something
}

有了auto以后,可以不显式地指定iter的类型:

std::vector<int> vec;
for (auto iter = vec.begin(); iter != vec.end(); iter++){
            // do something
}

而且如果vec的类型如果要改变的话(比如改成list),那么在第一种情况下,iter的类型需要改成std::list::const_iterator,而第二种的iter不需要更改。

我们还可以为auto添加修饰符。如:

const auto a = 123;		// const int
auto& b = vec.front();	// int &
for (const auto& c : vec) // const int &

auto与{}(initializer_list<T>)

在使用大括号作为初始化器时,也可以使用auto作类型推导,如:

auto a = { 1,2 };	// std::initializer_list<int>
auto b = { 3 };		// std::initializer_list<int>
auto c{ 4 };		// int
auto d = { 5,6.7 };	// error
auto e{ 8,9 };		// error

由以上的例子可以得知,如果期望的到一个initializer_list,则使用=加上{}初始化器。

decltype()修饰符

有的时候我们想声明一个变量,但是不想初始化它,此时,我们可以使用decltype(expr)。推断的结果就是表达式expr的类型。例如:

int var;
const int&& fx();
struct A { double x; }
const A* a = new A();

对以上的式子使用decltype可以得到:

类型 说明
decltype(fx()) const int && 函数fx的返回值类型
decltype(var) int 变量var的类型
decltype(a->x) double struct A的成员x的类型
posted @ 2020-11-06 15:04  Sigmun  阅读(149)  评论(0)    收藏  举报