我想让一个类的行为与指针相同,但还支持比较运算符,例如 <
和 >
.
我遇到了类型转换问题:
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/