【问题标题】:Multiple inheritance with templated template使用模板化模板进行多重继承
【发布时间】:2021-06-29 19:11:12
【问题描述】:

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

Godbolt link

Godbolt link with manual inheritance

#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&lt;class&gt; class ... Methods'

【问题讨论】:

  • 那么...问题是什么?你似乎有一些代码。该代码是否在某种程度上不起作用?如果是这样,你得到什么错误?此外,您实际上并不需要将this 指针传递给基类;他们已经有了一个,如果他们知道他们是T 的基类,那么他们可以static_cast&lt;T*&gt;(this) 获得指向派生类的指针。这是 CRTP 的一部分,是一个半通用的 C++ 工具。
  • 但是如果顶级类是模板,我如何将它们转换为基类?并且单个基类不知道顶级一级的整个模板列表。问题是 - 如何实现这一目标?我有编译错误,将编辑问题
  • @VladyslavMozhvylo 请在问题中填写所有相关信息。链接往往会过时。

标签: c++ templates metaprogramming variadic-templates c++20


【解决方案1】:

感谢@Nicol Bolas,他建议为此使用static_cast 和CRTP

#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();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-12
    • 2011-03-22
    • 2013-01-09
    • 2015-04-18
    • 2011-09-12
    • 2013-06-08
    相关资源
    最近更新 更多