use*_*517 2 c++ templates casting c++11
所以,我有这些结构的一些东西:
struct Generic {}
struct Specific : Generic {}
Run Code Online (Sandbox Code Playgroud)
在某些时候我需要向下转换,即:
Specific s = (Specific) GetGenericData();
Run Code Online (Sandbox Code Playgroud)
这是一个问题,因为我收到错误消息,指出没有用户定义的强制转换可用.
我可以将代码更改为:
Specific s = (*(Specific *)&GetGenericData())
Run Code Online (Sandbox Code Playgroud)
或者使用reinterpret_cast,它将是:
Specific s = *reinterpret_cast<Specific *>(&GetGenericData());
Run Code Online (Sandbox Code Playgroud)
但是,有没有办法让这个更干净?也许使用宏或模板?
我查看了这篇帖子的C++协变模板,我认为它有一些相似之处,但不知道如何根据我的情况重写它.我真的不想将事物定义为SmartPtr.我宁愿把东西当成它们的对象.
看起来GetGenericData()你的用法会返回一个Generic按值,在这种情况下,Specific由于对象切片,强制转换将是不安全的.
要做你想做的事,你应该让它返回一个指针或引用:
Generic* GetGenericData();
Generic& GetGenericDataRef();
Run Code Online (Sandbox Code Playgroud)
然后你可以执行演员:
// safe, returns nullptr if it's not actually a Specific*
auto safe = dynamic_cast<Specific*>(GetGenericData());
// for references, this will throw std::bad_cast
// if you try the wrong type
auto& safe_ref = dynamic_cast<Specific&>(GetGenericDataRef());
// unsafe, undefined behavior if it's the wrong type,
// but faster if it is
auto unsafe = static_cast<Specific*>(GetGenericData());
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
421 次 |
| 最近记录: |