【问题标题】:Specialize a template class?专门化一个模板类?
【发布时间】:2017-09-18 12:51:20
【问题描述】:

我正在尝试编写一个在没有循环或递归函数调用的情况下输出 1 到 1000 的程序,我想出了这个

#include <iostream>

template <int N>
class NumberGenerator : public NumberGenerator<N-1>{
    public:
    NumberGenerator();
};

template <int N>
NumberGenerator<N>::NumberGenerator(){
    // Let it implicitly call NumberGenerator<N-1>::NumberGenerator()
    std::cout << N << std::endl;
}

template <>
NumberGenerator<1>::NumberGenerator(){
     // How do I stop the implicit call?
     std::cout << 1 << std::endl;
}

int main(){
    NumberGenerator<1000> a; // Automatically calls the constructor
    return 0;
}

问题是,我无法停止链式调用(@​​987654322@ 仍然尝试调用NumberGenerator&lt;0&gt; 并无限下溢)。如何让链条停在 1?

【问题讨论】:

    标签: c++ template-specialization template-classes


    【解决方案1】:

    专门化类模板本身:

    template <int N>
    class NumberGenerator : public NumberGenerator<N-1>{
        public:
        NumberGenerator();
    };
    
    template <>
    class NumberGenerator<1> {
        public:
        NumberGenerator();
    };
    

    【讨论】:

    • 我能否使用NG&lt;1&gt; 中非专业类的其他功能? IE。 void NG&lt;N&gt;::foo() 是否覆盖 NG&lt;1&gt;
    • 呃。希望这可以帮助? coliru.stacked-crooked.com/a/dabc1b56b56e3848
    • 不,您将无法使用其他功能。要停止链,您必须删除基类。除了 1. 模板元编程(祝你好运) 2. 专业化类模板之外,没有其他办法
    • @ibug 不,除非您使用多重继承,并将所有常用方法放在基类中。
    • 这是另一种选择,视情况而定。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-12
    • 1970-01-01
    • 1970-01-01
    • 2013-01-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多