【问题标题】:how to get partial template work with subclass如何使部分模板与子类一起使用
【发布时间】:2019-05-23 06:29:20
【问题描述】:

我正在尝试使用结构和子结构制作通用模板, 但我的代码无法推断出正确的模板。 这是我的代码的抽象

#include <iostream>
using namespace std;
struct A{

};
struct B{

};
struct AA:public A{

};
struct BB:public B{

};

template<class container>
class Base{

};
template<class container>
class Derived:Base<container>{
    Derived() = delete;
};
template<>
class Derived<A>:Base<A>{

};
template<>
class Derived<B>:Base<B>{

};
int main() {
    Derived<AA> a;
    return 0;
}

出现错误

error: call to deleted constructor of 'Derived<AA>'

我希望struct A 及其子类可以与

template<>
class Derived<A>:Base<A>{

};

我该怎么做,或者我应该参考什么材料? 谢谢帮忙!

【问题讨论】:

    标签: c++ templates inheritance polymorphism


    【解决方案1】:

    你可以像这样使用偏特化

    // primary template
    template<class container, class = void>
    class Derived : Base<container> {
        Derived() = delete;
    };
    
    // partial specialization for A and its derived classes
    template<class container>
    class Derived<container, std::enable_if_t<std::is_base_of_v<A, container>>> : Base<container> {
    };
    

    如果有必要,还可以完全专业化。

    // full specialization for B
    template<>
    class Derived<B, void> : Base<B> {
    };
    

    LIVE

    【讨论】:

    • @jinzhenhui 觉得有用请回复accept
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-12
    • 2016-05-17
    • 2014-06-13
    • 2019-12-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多