c – 使用模板参数除以零

前端之家收集整理的这篇文章主要介绍了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.f2er.com/c/113451.html

猜你在找的C&C++相关文章