🐭 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
代理类是代理设计模式的具体应用,一般是为了使得类的接口与其它某些类保持一致或者遵循惯用法,刻意伪装,给人们一种假象。一般来说对客户端用户不可见,在设计上采用特殊手段隐藏了细节,主要是重载了特殊的运算符。
代码示例 :
#include <bitset>#include <iostream>#include <vector>int main(void) {using std::cout, std::is_same_v, std::vector, std::bitset;cout.setf(std::ios_base::boolalpha);// std::vector<bool>// vector<bool>::reference// std::vector<bool>::reference::operator=// std::vector<bool>::reference::operator boolvector<bool> vb(4, true);auto vb20 = vb[2];cout << is_same_v<decltype(vb20), bool> << '\n'; // falsecout << is_same_v<decltype(vb20), vector<bool>::reference> << '\n'; // truebool vb21 = vb[2];auto vb22 = static_cast<bool>(vb20);cout << is_same_v<decltype(vb21), bool> << '\n'; // truecout << is_same_v<decltype(vb22), bool> << '\n'; // true// std::bitset<N>// bitset<N>::reference// std::bitset<N>::reference::operator=// std::bitset<N>::reference::operator boolconst bitset<4> b(0b0101);auto b20 = b[2];cout << is_same_v<decltype(b20), bool> << '\n'; // falsecout << is_same_v<decltype(b20), bitset<4>::const_reference> << '\n'; // truebool b21 = b[2];auto b22 = static_cast<bool>(b20);cout << is_same_v<decltype(b21), bool> << '\n'; // truecout << is_same_v<decltype(b22), bool> << '\n'; // truereturn 0;}
:::tips 当 auto 与代理类一起工作的时候,由于 auto 没法调用代理类的特殊运算符重载函数,故而不能进行正确的类型推导,这个不是 auto 的问题,是 auto 的局限性。 :::
🐯 auto 与显式类型声明
auto 与代理类一起工作的时候,类型推导结果往往不是我们所期望的结果。另外,当我们本来就需要进行强制类型转换的场合,需要先进行转换然后再使用 auto 来接收结果。
代码示例 :
#include <iostream>#include <memory>#include <vector>int main(void) {char str[] = "1234567890";// std::memmove return void*, must cast to char*auto dest = static_cast<char *>(std::memmove(str + 4, str + 3, 3));std::cout << dest << '\n'; // 456890std::vector<int> vi{1, 2, 3, 4, 5, 6, 7, 8, 9, 0};auto mid = static_cast<std::vector<int>::size_type>(0.5 * vi.size());std::cout << vi[mid] << '\n'; // 6auto upi = std::make_unique<int>(42);// construct shared ptr from unique ptrstd::shared_ptr<int> spi = std::make_unique<int>(42);return 0;}
:::tips 可以从 std::unique_ptr 来构建 std::shared_ptr 这个特性非常有用,因此,对于一个类我们只需要提供一个返回 std::unique_ptr 类型的构造方法就可以满足多方面的需求。 :::
🐰 总结
- auto 不能很好的与代理类一起工作
- 显式类型声明与显式类型转换还有其存在价值
