0

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

Community
  • 1
  • 1
Martin R.
  • 67
  • 1
  • 4

1 Answers1

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

BlamKiwi
  • 2,093
  • 2
  • 19
  • 30
  • 1
    This question is *not* tagged as c++11. – vz0 Oct 30 '14 at 10:16
  • Maybe C++11 can do better, but what if I am not allowed to use the new features of C++11? – Martin R. Oct 30 '14 at 10:19
  • If he is restricted to C++03, there's always BOOST. – BlamKiwi Oct 30 '14 at 10:19
  • I can actually give some guarantee that the Boost implementation will work, if that's what you mean. Like how would that code you post behave if your example you had non public inheritance or an ambiguous base class? – BlamKiwi Oct 30 '14 at 10:26
  • I don't know exactly what you mean. The base class is ModuleFactory. I read the code like this: cast sth. to T* to check with static_cast if T* is somewhere in the inheritance 'tree' of ModuleFactory. If the base class `ModuleFactory`is sth. else the the code wouöd check if T* is type of 'sth. else' ?! Maybe its better to read if one would write sth. like this: `T* p; static_cast(p)`. I think this should be the same nut without a `reinterpret_cast` – Martin R. Oct 30 '14 at 10:41
  • @MartinR.: You need to initialize `p`, and you probably just want `ModuleFactory *q=p;` to control the direction of the inheritance. – Davis Herring Aug 18 '20 at 14:28