C++: Can virtual inheritance be detected at compile time?

后端 未结 8 426
被撕碎了的回忆
被撕碎了的回忆 2021-02-02 10:55

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

相关标签:
8条回答
  • 2021-02-02 11:51

    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.

    0 讨论(0)
  • 2021-02-02 11:55

    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.

    0 讨论(0)
提交回复
热议问题