什么是使用C ++透明类包装器 [英] What is the use of C++ Transparent Class Wrapper

查看:86
本文介绍了什么是使用C ++透明类包装器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


  1. 在C ++中调用透明类包装器

  2. 为什么调用透明...


欣赏一些概念性的解释。

Appreciate some conceptual explanation.

推荐答案

透明类包装器是一种类型的包装器,其中包装器的行为与底层类型相同 - 。

A transparent class wrapper is a wrapper around a type, where the wrapper behaves the same as the underlying type - hence "transparent".

下面是一个示例,其中包含 int 但是重载 operator ++()在使用时输出一条消息(受 this thread ):

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 this thread):

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 IntWrapper 如果我们选择:

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) { /* ... */ }

除非后者每次调用preincrement时都会打印一条消息。

Except the latter will print a message whenever preincrement is called.

注意,我提供了一个非显式的构造函数 IntWrapper(int i)。这确保了每当我使用 int ,其中需要 IntWrapper (例如 IntWrapper i = 0 ),编译器可以静默使用构造函数从 int IntWrapper c>。 Google C ++风格指南不鼓励单参数非显式构造函数,因为可能存在您没有期望的转换,这会伤害类型安全性。另一方面,这正是你想要的透明类封装器,因为你希望这两种类型可以很容易地转换。

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.

这是:

// ...
explicit IntWrapper(int i) ...
// ...
IntWrapper i = 0;   // this will now cause a compile error

这篇关于什么是使用C ++透明类包装器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆