面试题:什么是 C++ 中的 auto 和 decltype?

autodecltype 是 C++11 引入的两个关键字,用于简化代码和提高代码的可读性。

它们的主要作用是自动推导变量的类型,但它们的用途和行为有所不同。


auto 关键字

1. 作用

  • auto 用于自动推导变量的类型。
  • 编译器会根据变量的初始化表达式推导出变量的类型。

2. 使用场景

  • 简化复杂类型的声明。
  • 适用于迭代器、lambda 表达式、模板编程等场景。

3. 示例

#include <iostream>
#include <vector>

int main() {
    auto i = 42; // i 的类型推导为 int
    auto d = 3.14; // d 的类型推导为 double
    auto s = "hello"; // s 的类型推导为 const char*

    std::vector<int> vec = {1, 2, 3};
    auto it = vec.begin(); // it 的类型推导为 std::vector<int>::iterator

    std::cout << "i: " << i << ", d: " << d << ", s: " << s << std::endl;
    return 0;
}

4. 注意事项

  • auto 推导的类型会忽略引用和顶层 const
  • 如果需要保留引用或 const,可以使用 auto&const auto
  • 示例:
  int x = 10;
  const int& y = x;
  auto z = y; // z 的类型是 int,忽略 const 和引用
  auto& w = y; // w 的类型是 const int&

decltype 关键字

1. 作用

  • decltype 用于推导表达式的类型。
  • 它返回表达式的静态类型,包括引用和 const 修饰符。

2. 使用场景

  • 在需要精确推导表达式类型的场景中使用。
  • 常用于模板编程和返回类型推导。

3. 示例

#include <iostream>
#include <type_traits>

int main() {
    int x = 10;
    const int& y = x;
    decltype(y) z = x; // z 的类型是 const int&

    std::cout << "x: " << x << ", z: " << z << std::endl;
    return 0;
}

4. 注意事项

  • decltype 会保留表达式的引用和 const 修饰符。
  • decltype 可以用于推导复杂表达式的类型。
  • 示例:
  int x = 10;
  int* ptr = &x;
  decltype(*ptr) y = x; // y 的类型是 int&

autodecltype 的区别

特性autodecltype
推导依据根据初始化表达式推导类型根据表达式推导类型
引用和 const忽略引用和顶层 const保留引用和 const
使用场景简化变量声明精确推导表达式类型
示例auto x = 42;decltype(expr) x = value;

结合 autodecltype 使用

在 C++14 中,autodecltype 可以结合使用,用于推导函数的返回类型。例如:

template<typename T1, typename T2>
auto add(T1 a, T2 b) -> decltype(a + b) {
    return a + b;
}

int main() {
    auto result = add(3, 4.5); // result 的类型推导为 double
    std::cout << "result: " << result << std::endl;
    return 0;
}

总结

  • auto:用于自动推导变量类型,忽略引用和顶层 const
  • decltype:用于推导表达式类型,保留引用和 const
  • 两者结合可以提高代码的简洁性和可读性,尤其在模板编程和复杂类型推导中非常有用。

这个问题考察的是对 C++11 新特性的理解,尤其是 autodecltype 的使用场景和区别。

THE END
点赞12 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情代码图片

    暂无评论内容