gpt4 book ai didi

c++ - 在 C++ 编译时计算和打印阶乘

转载 作者:IT老高 更新时间:2023-10-28 23:27:45 45 4
gpt4 key购买 nike

template<unsigned int n>
struct Factorial {
enum { value = n * Factorial<n-1>::value};
};

template<>
struct Factorial<0> {
enum {value = 1};
};

int main() {
std::cout << Factorial<5>::value;
std::cout << Factorial<10>::value;
}

上面的程序在编译期间计算阶乘值。我想在编译时而不是在运行时使用 cout 打印阶乘值。我们如何在编译时打印阶乘值?

我正在使用 VS2009。

谢谢!

最佳答案

阶乘可以在编译器生成的消息中打印为:

template<int x> struct _;
int main() {
_<Factorial<10>::value> __;
return 0;
}

错误信息:

prog.cpp:14:32: error: aggregate ‘_<3628800> __’ has incomplete type and cannot be defined _::value> __; ^

这里 362880010 的阶乘。

在 ideone 上查看:http://ideone.com/094SJz

那么你在找这个吗?


编辑:

Matthieu 要求一个聪明的技巧来打印阶乘并让编译继续。这是一种尝试。它没有给出任何错误,因此编译成功并出现一个警告。

template<int factorial> 
struct _{ operator char() { return factorial + 256; } }; //always overflow
int main() {
char(_<Factorial<5>::value>());
return 0;
}

编译时出现以下警告:

main.cpp: In instantiation of '_::operator char() [with int factorial = 120]': main.cpp:16:39: required from here main.cpp:13:48: warning: overflow in implicit constant conversion [-Woverflow] struct _{ operator char() { return factorial + 256; } }; //always overflow

这里 1205 的阶乘。

ideone 演示:http://coliru.stacked-crooked.com/a/c4d703a670060545

你可以写一个不错的宏,然后用它来代替:

#define PRINT_AS_WARNING(constant) char(_<constant>())    

int main()
{
PRINT_AS_WARNING(Factorial<5>::value);
return 0;
}

那个 looks great .

关于c++ - 在 C++ 编译时计算和打印阶乘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4977715/

45 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com