C++ uses template recursion for compile-time computation

Sometimes, our code needs some specific values ​​(such as 2 to the Nth power). Note that the values ​​here must be written in the code, that is, constants. At this time, if you use the calculator to calculate one by one, it will be very troublesome, and the calculation during the operation will make the program run slowly. At this time, we use the compile-time calculation.
The main principle of compile-time computation is to use template recursion. For example, to calculate the factorial of N:

#include <iostream>
template<int n>
class C//主模板类
{
    
    
public:
	static const long long result = C<n - 1>::result * n;
};
template<>
class C<1>//模板特化,相当于递归终止条件
{
    
    
public:
	static const long long result = 1;
};
int main()
{
    
    
	std::cout << C<10>::result;
	return 0;
}

How can I prove that this is computed at compile time? static const long long result = 1;We can comment out this sentence of C<1> first and check the error message:
Error message
it can be seen from this that it will be calculated during compilation. Moreover, the calculation during compilation has the advantage that if infinite recursion occurs, the compiler will give an error message:Error message

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324087683&siteId=291194637