I would like to determine at compile time if a pointer to Derived can be cast from a pointer to Base without dynamic_cast<>. Is this possible using templates and metaprogramm
I had the same problem, once. Unfortunately, I'm not quite sure about the virtual-problem. But: Boost has a class named is_base_of
(see here) which would enable you to do smth. like the following
BOOST_STATIC_ASSERT((boost::is_base_of<Foo, Bar>::value));
Furthermore, there's a class is_virtual_base_of
in Boost's type_traits
, maybe that's what you're looking for.
There is a template hack to do it at compile time.
First you need to create an interface class like this:
template <typename T>
class SomeInterface
{
public:
inline int getSomething() const;
};
template<typename T>
inline int SomeInterface<T>::getSomething() const
{
return static_cast<T const*>(this)->T::getSomething();
}
The idea is: Cast this
to T
and call method with the same name and the same arguments from it.
As you can see the wrapper function is inline so there will be no performance or call stack overheads during runtime.
And then create classes implementing the interface like this:
class SomeClass : public SomeInterface<SomeClass>
{
friend class SomeInterface<SomeClass>;
public:
int getSomething() const;
};
Then just add implementations of the derived methods normally.
This way might not look beautiful but exactly does the job.