c++ - 重载强制转换以使类的行为与指针相同时的正确行为

标签 c++ casting operator-overloading

我想让一个类的行为与指针相同,还支持比较运算符,例如 <> .

我遇到了类型转换问题:

ptr_t<foo> x = new foo;
(bar*)x;              // cast should be allowed
static_cast<bar*>(x); // cast should fail

上面的片段应该表现得像ptr_t<foo>foo* .

这里是转换运算符:

template <typename cast_t>
explicit inline operator cast_t() {
  return (cast_t)(ptr); // causes static_cast to use C-style, which is bad
}

如果我在定义中使用 C 风格,那么 static_cast变得不安全。如果我使用 static_cast然后 C 风格变得不那么有用了。我该如何解决这个问题?

最佳答案

您可以轻松模拟 ptr_t<foo>表现得像foo*通过重载箭头和取消引用运算符,同时提供 get功能。这就是所有智能指针的操作方式(按照惯例),并且使用起来更加自然。摆弄类型转换似乎不必要地复杂和脆弱。

template <typename T>
struct ptr_t
{
    T* get() const;

    T* operator->() const
    {
        return get();
    }

    T& operator*() const
    {
        return *get();
    }
};

struct foo
{
    void bar() const;
};

void baz(foo*);

ptr_t<foo> x = /* .. */;

x->bar();
(*x).bar();
baz(x.get());

关于c++ - 重载强制转换以使类的行为与指针相同时的正确行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8351573/

相关文章:

c++ - gmtime算法的最小实现?

c++ - 如何在 SystemC 中创建自定义 channel ?

c++ - 为什么找到 f1 但找不到 f2?

java - 向下转换对象的时间复杂度是多少?

c++ - 确定类是否实现 operator() 的任何方法

c++ - 使用模板的运算符重载

c++ - 数组中是否也可以动态删除内存?

c++ - 同一地址的变量如何产生 2 个不同的值?

java - 类型转换后 "Cannot find symbol"

c++ - 重载 >> 使用 istream