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

后端 未结 8 430
被撕碎了的回忆
被撕碎了的回忆 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:55

    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.

提交回复
热议问题