小编Exx*_*xul的帖子

模板元编程

有人可以向我解释一下,为什么第一个模板元编程方式将进入无限循环,而第二个模板正确运行。

#include <iostream>
using namespace std;

template<int N, int M>
struct commondivs {                                              
  static const int val = (N<M) ? commondivs<N,(M-N)>::val : commondivs<(N-M),M>::val;
};

template<int N>
struct commondivs<N,N> {
  static const int val = N;
};


int commondiv(int N, int M){
    if(N==M){
        return N;
    }   
    return (N<M)?commondiv(N,(M-N)):commondiv((N-M),M);     
}

int main() {

    cout << commondivs<9,6>::val << endl;
    cout << commondiv(9,6) << endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

c++ templates template-meta-programming

29
推荐指数
3
解决办法
2401
查看次数

标签 统计

c++ ×1

template-meta-programming ×1

templates ×1