Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

division by zero with a template argument

Tags:

c++

templates

I have a template

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

when I instantiate this with 0

Foo<0> bar;

gcc is too smart and reports division by zero at compile time

I tried

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

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

but this gives me error:

error: explicit specialization in non-namespace scope 'class Foo' error: template-id 'bar<0>' in declaration of primary template

any ideas how I could solve/workaround this?

like image 621
gsf Avatar asked Dec 05 '14 22:12

gsf


1 Answers

You can always rethink the formula:

template<size_t N>
class Foo {
    bool bar() {
        return N == 0 || (N >=5 && N < 10);
    }
 }
like image 122
Eclipse Avatar answered Sep 22 '22 12:09

Eclipse