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
There is a template hack to do it at compile time.
First you need to create an interface class like this:
template
class SomeInterface
{
public:
inline int getSomething() const;
};
template
inline int SomeInterface::getSomething() const
{
return static_cast(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
{
friend class SomeInterface;
public:
int getSomething() const;
};
Then just add implementations of the derived methods normally.
This way might not look beautiful but exactly does the job.