c – 使用模板参数除以零

我有一个模板
template<size_t N>
class Foo {
    int bar(int a) {
        if (N == 0)
            return 0;
        return a / N;
    }
 }

当我用0实例化它

Foo<0> bar;

gcc太聪明了,在编译时报告除零

我试过了

class Foo<size_t N> {
    template<size_t M>
    int bar(int a) {
        return a / N;
    }

    template<>
    int bar<0>(int a) {
        return 0;
    }
 };

但这给了我错误

错误:非命名空间范围’class Foo’中的显式特化
错误:template-id’bar< 0>‘在主要模板的声明中

我有什么想法可以解决/解决这个问题?

解决方法

您可以为Foo< 0>创建模板特化.
template <>
class Foo<0> {
public:
    bool bar () { return true; }
};

如果您只想单独使用bar解决问题,而不是触及Foo的任何其他部分,则可以创建一个伴随方法来避免此问题:

template <size_t N>
class Foo
{
    bool bar(int n) {
        if (n == 0) return true;
        return 5 / n == 1;
    }
public:
    bool bar() { return bar(N); }
};

或者将该方法的实现拉出到自己的类中,并将其专门化:

template <size_t N>
class Bar
{
public:
    bool operator() const { return 5 / N == 1; }
};

template <>
class Bar<0>
{
public:
    bool operator() const { return true; }
};

template <size_t N>
class Foo {
    bool bar() { return Bar<N>()(); }
};

或者,您可以使用Jarod42的建议,并专门化该方法本身(这里重申的答案是完整性).

template <size_t N>
class Foo
{
public:
    bool bar() { return 5 / N == 1; }
};

template <> inline bool Foo<0>::bar() { return true; }

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...