微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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; }

原文地址:https://www.jb51.cc/c/113451.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐