🐭 auto 的本质与局限性

auto 在绝大多数时候都能很好的工作,因为它就是机械的,忠实的从初始化物来推导类型。当 auto 不能满足要求的时候,往往是因为初始化物的类型不能满足要求,这个不是 auto 的问题。当这种情况出现的时候,我们就需要显式的声明类型或者进行显式的类型转换。

🐂 STL 中的代理类

STL 里面主要有下面两个代理类:

std::vector::reference std::bitset::reference https://en.cppreference.com/w/cpp/container/vector_bool/reference https://en.cppreference.com/w/cpp/utility/bitset/reference

代理类是代理设计模式的具体应用,一般是为了使得类的接口与其它某些类保持一致或者遵循惯用法,刻意伪装,给人们一种假象。一般来说对客户端用户不可见,在设计上采用特殊手段隐藏了细节,主要是重载了特殊的运算符。
代码示例 :

  1. #include <bitset>
  2. #include <iostream>
  3. #include <vector>
  4. int main(void) {
  5. using std::cout, std::is_same_v, std::vector, std::bitset;
  6. cout.setf(std::ios_base::boolalpha);
  7. // std::vector<bool>
  8. // vector<bool>::reference
  9. // std::vector<bool>::reference::operator=
  10. // std::vector<bool>::reference::operator bool
  11. vector<bool> vb(4, true);
  12. auto vb20 = vb[2];
  13. cout << is_same_v<decltype(vb20), bool> << '\n'; // false
  14. cout << is_same_v<decltype(vb20), vector<bool>::reference> << '\n'; // true
  15. bool vb21 = vb[2];
  16. auto vb22 = static_cast<bool>(vb20);
  17. cout << is_same_v<decltype(vb21), bool> << '\n'; // true
  18. cout << is_same_v<decltype(vb22), bool> << '\n'; // true
  19. // std::bitset<N>
  20. // bitset<N>::reference
  21. // std::bitset<N>::reference::operator=
  22. // std::bitset<N>::reference::operator bool
  23. const bitset<4> b(0b0101);
  24. auto b20 = b[2];
  25. cout << is_same_v<decltype(b20), bool> << '\n'; // false
  26. cout << is_same_v<decltype(b20), bitset<4>::const_reference> << '\n'; // true
  27. bool b21 = b[2];
  28. auto b22 = static_cast<bool>(b20);
  29. cout << is_same_v<decltype(b21), bool> << '\n'; // true
  30. cout << is_same_v<decltype(b22), bool> << '\n'; // true
  31. return 0;
  32. }

:::tips 当 auto 与代理类一起工作的时候,由于 auto 没法调用代理类的特殊运算符重载函数,故而不能进行正确的类型推导,这个不是 auto 的问题,是 auto 的局限性。 :::

🐯 auto 与显式类型声明

auto 与代理类一起工作的时候,类型推导结果往往不是我们所期望的结果。另外,当我们本来就需要进行强制类型转换的场合,需要先进行转换然后再使用 auto 来接收结果。
代码示例 :

  1. #include <iostream>
  2. #include <memory>
  3. #include <vector>
  4. int main(void) {
  5. char str[] = "1234567890";
  6. // std::memmove return void*, must cast to char*
  7. auto dest = static_cast<char *>(std::memmove(str + 4, str + 3, 3));
  8. std::cout << dest << '\n'; // 456890
  9. std::vector<int> vi{1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
  10. auto mid = static_cast<std::vector<int>::size_type>(0.5 * vi.size());
  11. std::cout << vi[mid] << '\n'; // 6
  12. auto upi = std::make_unique<int>(42);
  13. // construct shared ptr from unique ptr
  14. std::shared_ptr<int> spi = std::make_unique<int>(42);
  15. return 0;
  16. }

:::tips 可以从 std::unique_ptr 来构建 std::shared_ptr 这个特性非常有用,因此,对于一个类我们只需要提供一个返回 std::unique_ptr 类型的构造方法就可以满足多方面的需求。 :::

🐰 总结

  1. auto 不能很好的与代理类一起工作
  2. 显式类型声明与显式类型转换还有其存在价值