在编译时找到最大公约数

Find greatest common divisor at compile time

本文关键字:最大公约数 编译      更新时间:2023-10-16

我正在尝试使用模板在编译时找到最大公约数。请考虑以下代码:

#include "stdafx.h"
#include <iostream>
template<int N, int M, int K>
class A{
public:
    static const int a=A<M,K,M%K>::a;
};
template<int N, int M>
class A<N,M,0>{
public:
    static const int a=M;
};
int _tmain(int argc, _TCHAR* argv[])
{
    std::cout << A<11,13,11>::a;
    return 0;
}

这段代码可以工作,但是如果我尝试编写

#include "stdafx.h"
#include <iostream>
template<int N, int M>
class GCD{
public:
    static const int a=A<N,M,N%M>::a;
};
template<int N, int M, int K>
class A{
public:
    static const int a=A<M,K,M%K>::a;
};
template<int N, int M>
class A<N,M,0>{
public:
    static const int a=M;
};
int _tmain(int argc, _TCHAR* argv[])
{
    std::cout << GCD<11,13>::a;
    return 0;
}

我有崩溃错误 C2059"常量"。

为什么这段代码不起作用?

您需要

在顶部为A进行前向声明:

template<int N, int M, int K>
class A;

然后它在符合标准的编译器上工作正常。或者你可以把GCD移到所有A的东西下面。

现场示例