c++ - division by zero with a template argument -


i have template

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

when instantiate 0

foo<0> bar; 

gcc smart , reports division 0 @ compile time

i tried

class foo<size_t n> {     template<size_t m>     int bar(int a) {         return / n;     }      template<>     int bar<0>(int a) {         return 0;     }  }; 

but 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 solve/workaround this?

you can create template specialization foo<0>.

template <> class foo<0> { public:     bool bar () { return true; } }; 

if want address issue bar alone, , not touch other part of foo, can create companion method avoid issue:

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

or pull implementation of method out own class, , specialize that:

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

alternatively, can use jarod42's suggestion, , specialize method (answer reiterated here completeness).

template <size_t n> class foo { public:     bool bar() { return 5 / n == 1; } };  template <> inline bool foo<0>::bar() { return true; } 

Comments

Popular posts from this blog

python - mat is not a numerical tuple : openCV error -

c# - MSAA finds controls UI Automation doesn't -

wordpress - .htaccess: RewriteRule: bad flag delimiters -