重载 C++ 类型转换(函数)

2024-01-13

使用 C++ 风格的类型转换(全部 4 种)看起来与某些类型完全一样函数模板. e.g.

template<typename TO, typename FROM>
TO dynamic_cast (FROM p);

将被用作,

dynamic_cast<Derived*>(p); // p is Base*

为什么不允许超载按自定义使用的语言标准? (就像我们可以重载关键字一样new/delete或其他operators)


为什么不允许超载按自定义使用的语言标准?

我想这是因为标准委员会在介绍这些时,认为所有这四种类型转换的语义都定义良好,并且适用于它们应该是的所有类型。大多数情况下,这是真的。

我所知道的唯一反例是无法dynamic_cast智能指针实例之间:

shared_ptr<Derived> pd = dynamic_cast<shared_ptr<Derived> >(pb);

我想这样做的能力会有一些优点。

I don't know whether this has been discussed by the volunteers that did all the work in the standards committee (and I'm too lazy to google), but if it has been discussed (and I'd think so), it's been rejected either because someone thought the disadvantages outweigh the advantages, or because nobody had found the time to make a decent proposal and shepherd it through.1


1 Don't laugh. There's actually a lot of things most agree would be nice to have, and which are only failing to materialize because nobody could be bothered to do the work of writing a decent proposal, and spending the time needed to discuss and to iteratively improve it until it can be voted on.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

重载 C++ 类型转换(函数) 的相关文章

随机推荐