Using reinterpret_cast to check inheritance at compile time

﹥>﹥吖頭↗ 提交于 2019-12-13 09:33:53

问题


Regarding this question: When to use reinterpret_cast?

I found sth. like this:

template<typename T> bool addModuleFactoryToViewingFactory(ViewingPackage::ViewingFactory* pViewingFactory)
{
 static_cast<ModuleFactory*>(reinterpret_cast<T*>(0)); // Inheritance compile time check

  ...
}

Is this a good way to check whether T can be casted to ModuleFactory at compile time?
I mean, to check if the programmer put valid stuff into the <>of addModuleFactoryToViewingFactory<T>(...)
Is this okay, good or maybe the only way?

Greetings


回答1:


You're trying to solve a problem that doesn't need to be solved. Since C++11, we have Type Traits that allow us to check things like this explicitly in Template Metaprogramming.

For example, is_base_of

http://en.cppreference.com/w/cpp/types/is_base_of



来源:https://stackoverflow.com/questions/26649987/using-reinterpret-cast-to-check-inheritance-at-compile-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!