加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 使用模板参数除以零

发布时间:2020-12-16 05:53:22 所属栏目:百科 来源:网络整理
导读:我有一个模板 templatesize_t Nclass Foo { int bar(int a) { if (N == 0) return 0; return a / N; } } 当我用0实例化它 Foo0 bar; gcc太聪明了,在编译时报告除零 我试过了 class Foosize_t N { templatesize_t M int bar(int a) { return a / N; } templat
我有一个模板
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; }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读