
Question:
<ol><li>What is call "Transparent Class Wrapper" in C++</li> <li>Why it is call "Transparent..."</li> <li>What is the use of it (What cannot do without 'Transparent Class Wrapper').</li> </ol>
Appreciate some conceptual explanation.
Answer1:A transparent class wrapper is a wrapper around a type, where the wrapper behaves the same as the underlying type - hence "transparent".
To explain it as well as its use, here's an example where we wrap an int
but overload operator++()
to output a message whenever it is used (inspired by <a href="http://bytes.com/topic/c/answers/428034-transparent-class-wrapper" rel="nofollow">this thread</a>):
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 ...
};
We can then replace usages of int
with IntWrapper
if we choose to:
for (int i = 0; i < 100; ++i) { /* ... */ }
// becomes
for (IntWrapper i = 0; i < 100; ++i) { /* ... */ }
Except the latter will print a message whenever preincrement is called.
Note that I supplied a non-explicit constructor IntWrapper(int i)
. This ensures that whenever I use an int
where an IntWrapper
is expected (such as IntWrapper i = 0
), the compiler can silently use the constructor to create an IntWrapper
out of the int
. The Google C++ style Guide discourages single-argument non-explicit constructors for precisely this reason, as there may be conversions where you didn't expect, which hurts type safety. On the other hand, this is exactly what you want for transparent class wrappers, because you do want the two types to be readily convertible.
That is:
// ...
explicit IntWrapper(int i) ...
// ...
IntWrapper i = 0; // this will now cause a compile error
Answer2:Most likely, you're referring to a lightweight inline (header file) wrapper class, though I'm not familiar with the term. Adding a level of abstraction like this is useful in permitting generic client code.