c++ - 使用模板化模板的多重继承

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

我想通过模板参数进行多重继承并将引用传递给 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<class> class ... Methods'

最佳答案

感谢 @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();
}

关于c++ - 使用模板化模板的多重继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66927346/

相关文章:

java - Spring MVC 和类似 Facelets 的模板引擎

c++ - 确定模板化类型是否是动态的

lua - 通过 __index 进行元方法查找?

c++ - 另一个 "OpenGL Not Drawing"问题

C++自动检测模板参数?

c++ - reinterpret_cast 类型转换成本

c++ - 模板化基类还有一个共同的基类指针?

c++ - 模板 SFINAE 在 conditional_t 内

c++ - 如何转换嵌套的 C++11 绑定(bind)表达式

c++ - glm::rotate 导致纹理膨胀