首页 > 解决方案 > 使用模板化模板进行多重继承

问题描述

我想通过模板参数进行多重继承并this在每个基类中传递对的引用,所以我可以从每个基类的方法中调用顶级对象的方法。我可以通过手动继承来做到这一点,但我希望能够通过模板参数来做到这一点。

螺栓链接

手动继承的Godbolt链接

#include <cstdio>

template <typename T>
struct Foo {
    Foo(T &t)
        : t_(t) {

    }

    void foo() {
        t_.call("foo");
    }

    T &t_;
};

template <typename T>
struct Bar {
    Bar(T &t)
        : t_(t) {

    }

    void bar() {
        t_.call("bar");
    }

    T &t_;
};

template <template<typename> typename... Methods>
struct Impl : public Methods<Impl>... {
    Impl() 
        : Methods<Impl>(*this)... {

    }

    void call(const char *m) {
        printf(m);
    }
};

int main() {
    auto t = Impl<Foo, Bar>();

    t.foo();
    t.bar();
}

我尝试了这种方法,但它给出了 type/value mismatch at argument 1 in template parameter list for 'template<class> class ... Methods'

标签: c++templatesmetaprogrammingvariadic-templatesc++20

解决方案


感谢@Nicol Bolas,他建议为此使用static_castCRTP

#include <cstdio>

template <typename T>
struct Foo {
    void foo() {
        static_cast<T*>(this)->call("foo");
    }
};

template <typename T>
struct Bar {
    void bar() {
        static_cast<T*>(this)->call("bar");
    }
};

template <template<typename> typename... Methods>
struct Impl : public Methods<Impl<Methods...>>... {
    Impl() {

    }

    void call(const char *m) {
        printf(m);
    }
};

int main() {
    auto t = Impl<Foo, Bar>();

    t.foo();
    t.bar();
}

推荐阅读