c – 使用模板参数除以零

前端之家收集整理的这篇文章主要介绍了c – 使用模板参数除以零前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个模板
  1. template<size_t N>
  2. class Foo {
  3. int bar(int a) {
  4. if (N == 0)
  5. return 0;
  6. return a / N;
  7. }
  8. }

当我用0实例化它

  1. Foo<0> bar;

gcc太聪明了,在编译时报告除零

我试过了

  1. class Foo<size_t N> {
  2. template<size_t M>
  3. int bar(int a) {
  4. return a / N;
  5. }
  6.  
  7. template<>
  8. int bar<0>(int a) {
  9. return 0;
  10. }
  11. };

但这给了我错误

错误:非命名空间范围’class Foo’中的显式特化
错误:template-id’bar< 0>‘在主要模板的声明中

我有什么想法可以解决/解决这个问题?

解决方法

您可以为Foo< 0>创建模板特化.
  1. template <>
  2. class Foo<0> {
  3. public:
  4. bool bar () { return true; }
  5. };

如果您只想单独使用bar解决问题,而不是触及Foo的任何其他部分,则可以创建一个伴随方法来避免此问题:

  1. template <size_t N>
  2. class Foo
  3. {
  4. bool bar(int n) {
  5. if (n == 0) return true;
  6. return 5 / n == 1;
  7. }
  8. public:
  9. bool bar() { return bar(N); }
  10. };

或者将该方法的实现拉出到自己的类中,并将其专门化:

  1. template <size_t N>
  2. class Bar
  3. {
  4. public:
  5. bool operator() const { return 5 / N == 1; }
  6. };
  7.  
  8. template <>
  9. class Bar<0>
  10. {
  11. public:
  12. bool operator() const { return true; }
  13. };
  14.  
  15. template <size_t N>
  16. class Foo {
  17. bool bar() { return Bar<N>()(); }
  18. };

或者,您可以使用Jarod42的建议,并专门化该方法本身(这里重申的答案是完整性).

  1. template <size_t N>
  2. class Foo
  3. {
  4. public:
  5. bool bar() { return 5 / N == 1; }
  6. };
  7.  
  8. template <> inline bool Foo<0>::bar() { return true; }

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