【发布时间】:2011-12-02 03:51:28
【问题描述】:
我想让一个类的行为与指针相同,但也支持比较运算符,如< 和>。
我遇到了铸造麻烦:
ptr_t<foo> x = new foo;
(bar*)x; // cast should be allowed
static_cast<bar*>(x); // cast should fail
上面的 sn-p 应该表现得好像 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 风格就变得没那么有用了。我该如何解决这个问题?
【问题讨论】:
-
您为什么希望
static_cast失败?这对我来说毫无意义。 -
@R.MartinhoFernandes
ptr<foo>应该具有与foo*相同的行为。foo和bar是不相关的类。 -
我不认为你可以告诉编译器将
ptr_t<foo>与foo*完全匹配以获得乐趣,并且你需要让 C 风格的演员做一个reinterpret_cast对你来说,没有转换运算符(这将使static_cast工作)。
标签: c++ casting operator-overloading