转换指针和三元?:运算符。我重新发明了轮子吗? [英] Casting pointers and the ternary ?: operator. Have I reinvented the wheel?

查看:212
本文介绍了转换指针和三元?:运算符。我重新发明了轮子吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码的最后一行无法编译 castingAndTernary.cpp:15:error:不同指针类型D1 *和D2 *之间的条件表达式缺少转换

The last line of this code fails to compile with castingAndTernary.cpp:15: error: conditional expression between distinct pointer types ‘D1*’ and ‘D2*’ lacks a cast

一个真正聪明的编译器没有问题,因为两者都可以安全地转换为 B * 类)。我不愿意使用static_cast和dynamic_cast等等 - 我担心我会混合类有一天和得到未定义的行为。这就是为什么我创建了up_cast模板。此模板在允许的转换中实现最低限度。有更简单的方法吗?还有其他的解决方法,但我不禁想到,有一些更简单和更安全,我可以使用?

A really smart compiler could have no difficulty because both can be safely casted to B* (the base class). I'm reluctant to use static_cast and dynamic_cast and so on - I'm worried that I'll mix up the classes someday and get undefined behaviour. That's why I created the up_cast template. This template does the bare minimum in allowed conversion. Is there a simpler way? There are other workarounds, but I can't help but think that there's something even simpler and safer that I could use?

struct B{ };
struct D1 : public B{ };
struct D2 : public B{ };

template<typename T,typename V>
T up_cast(V x) {
        return x;
}
int main() {
        bool boolean_expression = true;
        B * b;
        b = new D1;
        b = new D2;
        b = boolean_expression ? up_cast<B*>(new D1) : up_cast<B*>(new D2);
        b = boolean_expression ? new D1 : new D2;
}

g ++(Ubuntu 4.3.3-5ubuntu4)4.3.3

g++ (Ubuntu 4.3.3-5ubuntu4) 4.3.3

更新名称从 implicit_cast 更改为 up_cast 根据@ Konrad的回答

Update changed name from implicit_cast to up_cast as per @Konrad's answer

推荐答案


一个真正聪明的编译器可以没有困难,安全地转换为 B *

标准强制此行为。一个真正聪明的编译器表现如观察。

Irrelevant. The standard mandates this behaviour. A really smart compiler behaves as observed.

使用你的自定义转换实际上是很好的(你不愿意使用显式转换)。但是,我将使用不同的名称: upcast - 因为这发生在这里:在继承层次结构中向上转换。

The use of your custom cast is actually fine (and your reluctance for using an explicit cast is well-placed). However, I’d use a different name: upcast – since that’s happening here: a cast upwards in the inheritance hierarchy.

这篇关于转换指针和三元?:运算符。我重新发明了轮子吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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