c++11 新特性学习 ————decltype 类型推导
decltype是 C++11 引入的一个关键字,用于查询表达式的类型。它可以在不实际计算表达式值的情况下推导出该表达式的类型。这对于编写模板代码和类型推导特别有用。下面通过一些从简单到复杂的代码示例来展示decltype的用法。
·
decltype 是 C++11 引入的一个关键字,用于查询表达式的类型。它可以在不实际计算表达式值的情况下推导出该表达式的类型。这对于编写模板代码和类型推导特别有用。下面通过一些从简单到复杂的代码示例来展示 decltype 的用法。
1. 基本用法
首先,我们从最简单的用法开始,直接推导变量的类型。
#include <iostream> |
|
int main() { |
|
int x = 5; |
|
decltype(x) y = 10; // y 的类型将被推导为 int |
|
std::cout << "y: " << y << std::endl; |
|
return 0; |
|
} |
2. 推导复杂表达式的类型
decltype 也可以用于推导复杂表达式的类型。
#include <iostream> |
|
int main() { |
|
int x = 5; |
|
int y = 10; |
|
decltype(x + y) z = 15; // z 的类型将被推导为 int,因为 x + y 的类型是 int |
|
std::cout << "z: " << z << std::endl; |
|
return 0; |
|
} |
3. 与 auto 结合使用
decltype 常与 auto 结合使用,以便在需要类型推导但又不能直接使用 auto 的地方使用。
#include <iostream> |
|
struct MyStruct { |
|
int a; |
|
double b; |
|
}; |
|
int main() { |
|
|
auto it = &s.b |
|
decltype(it) it2 = &s.b ;// it2 的类型将被推导为 double* |
|
std::cout << "*it2: " << *it2 << std::endl; |
|
return 0; |
|
} |
4. 用于模板编程
在模板编程中,decltype 非常有用,因为它可以帮助我们推导模板参数的类型。
#include <iostream> |
|
template <typename T1, typename T2> |
|
auto add(T1 x, T2 y) -> decltype(x + y) { |
|
return x + y; |
|
} |
|
int main() { |
|
auto result = add(3, 4.5); // result 的类型将被推导为 double |
|
std::cout << "result: " << result << std::endl; |
|
return 0; |
|
} |
5. 推导函数返回类型
decltype 也可以用于推导函数的返回类型。
#include <iostream> |
|
int foo(int x) { |
|
return x * x; |
|
} |
|
int main() { |
|
decltype(foo(5)) y = 25; // y 的类型将被推导为 int,因为 foo(5) 的返回类型是 int |
|
std::cout << "y: " << y << std::endl; |
|
return 0; |
|
} |
通过这些示例,我们可以看到 decltype 在 C++ 中的强大功能,它能够在编译时推导出复杂的类型,从而使代码更加灵活和健壮。
更多推荐
所有评论(0)