Curiously Recurring Template and Template parameter dependent subclassing issues

 ̄綄美尐妖づ 提交于 2019-12-04 09:43:18

Normally, if you want A to inherit from B, then B cannot know anything about A other than it's declaration:

template < class __object >
struct Derived;

Unfortunately, you want to get more, so you'll have to use a type trait:

template<class __derived>
struct Base_traits {
    //using Object = ?????;
};
template<class __object>
struct Base_traits<Derived<__object>> {
    using Object = __object; //note, this also can't inspect B.
};

The Base class can inspect the Base_traits all it wants, because the traits don't inspect B at all.

template < class __derived, class __object = typename Base_traits<__derived>::Object >
struct Base {
    using Derived = __derived;
    using Object = typename Base_traits<__derived>::Object;
    //or        
    using Object = __object;


Unrelated, leading double underscores are disallowed for use by mortals, use a single leading underscore followed by a lowercase letter. Alternatively, use a trailing underscore.

Also, the syntax

void function(Object o) { return Derived::function(s); }

Won't work, because that notation cannot be used for upcasts, only downcasts. Ergo, you have to use static_cast on the this. Since that's vaguely ugly, I put it behind a function:

    void foo(Object o) { self()->bar(o); }
private:
    __derived* self() {return static_cast<__derived*>(this);}
    const __derived* self() const {return static_cast<__derived*>(this);}
};

Full code: http://coliru.stacked-crooked.com/a/81595b0fcd36ab93

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!