- 什么是 C++ 中的“透明类包装器”
- 为什么叫“透明...”
- 它有什么用(没有“透明类包装器”就不能做什么)。
欣赏一些概念性的解释。
透明类包装器是围绕类型的包装器,其中包装器的行为与基础类型相同 - 因此是“透明的”。
为了解释它以及它的使用,这里有一个例子,我们包装一个int
但重载以在使用它时输出一条消息(受此线程operator++()
启发):
class IntWrapper {
int data;
public:
IntWrapper& operator++() {
std::cout << "++IntWrapper\n";
data++;
return *this;
}
IntWrapper(int i) : data(i) {}
IntWrapper& operator=(const IntWrapper& other)
{
data = other.data;
return *this;
}
bool operator<(const IntWrapper& rhs) const { return data < rhs.data; }
// ... other overloads ...
};
然后,如果我们选择,我们可以替换int
with的用法:IntWrapper
for (int i = 0; i < 100; ++i) { /* ... */ }
// becomes
for (IntWrapper i = 0; i < 100; ++i) { /* ... */ }
除了后者会在调用 preincrement 时打印一条消息。
请注意,我提供了一个非显式构造函数IntWrapper(int i)
。这确保了每当我使用预期的int
位置IntWrapper
(例如IntWrapper i = 0
)时,编译器可以静默地使用构造函数IntWrapper
从int
. 正是出于这个原因,Google C++ 风格指南不鼓励使用单参数非显式构造函数,因为可能会出现您没有预料到的转换,这会损害类型安全。另一方面,这正是您想要的透明类包装器,因为您确实希望这两种类型易于转换。
那是:
// ...
explicit IntWrapper(int i) ...
// ...
IntWrapper i = 0; // this will now cause a compile error
最有可能的是,您指的是轻量级内联(头文件)包装器类,尽管我不熟悉该术语。添加这样的抽象级别对于允许通用客户端代码很有用。