我有一个模板
- 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;
- }
- };
但这给了我错误:
解决方法
您可以为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; }