打印用于模板元编程的静态变量
print static variable for template metaprogramming
我有以下阶乘的模板元编程实现:
#include <iostream>
template <int n> struct factorial{
static const int res = n*factorial<n-1>::res;
};
template <> struct factorial<0>{
static const int res = 1;
};
int main(){
std::cout << factorial<5>::res << 'n';
return 0;
}
此代码编译成功并按预期输出 120。但是,出于纯粹的自我享受原因,我想让它不编译,而是在编译器的错误消息中显示 120。
是否有一个简单的语法错误,我可以故意输入到我的代码中,让它无法编译,但仍在编译器错误消息中打印值 5!,即 120?
我预计答案可能会取决于编译器;我目前正在使用Xcode Mac OSX附带的g ++,iirc是clang的前端。
您可以使用已声明但未定义的模板将值打印为编译时错误。
template<int n>
class display;
template<int n> struct factorial{
static const int res = n*factorial<n-1>::res;
};
template<> struct factorial<0>{
static const int res = 1;
};
int main()
{
display<factorial<5>::res> value;
}
G++ 输出:
g++ -std=c++11 fact.cxx
fact.cxx: In function ‘int main()’:
fact.cxx:14:29: error: aggregate ‘display<120> value’ has incomplete type and cannot be defined
display<factorial<5>::res> value;
^
如果允许选项 -Werror
或者警告计为错误,请执行以下操作:
#include <iostream>
template <int n> struct factorial{
static const int res = n*factorial<n-1>::res;
};
template <> struct factorial<0>{
static const int res = 1;
};
int main(){
char x[factorial<5>::res];
return x[sizeof(x)];
}
将产生错误/警告
错误:"x[120ul]"在此函数中使用未初始化 [-Werror=未初始化]
使用 GCC 5.3 或
错误:数组索引 120超过数组的末尾(包含 120 个元素)[-Werror,-Warray-bounds]
使用 clang 3.8。
相关文章:
- 在 .h 文件中的类中声明静态变量和在.cpp文件中声明"global"变量有什么区别
- 模板基类中的静态变量
- 类和静态变量
- 不同作用域中的静态变量和全局变量
- 静态变量声明和定义
- 是否可以依赖函数范围的静态变量来执行程序关闭期间调用的方法?
- 在类中继承静态变量?
- "local scope"中的 C++ 初始化静态变量
- 使用静态变量的递归调用的不同输出
- 复制文件流C++静态变量
- 跨模板化函数编译的静态变量
- C++编译器是否优化了顺序静态变量读取?
- C++,每个循环初始化一个新的静态变量
- (为什么)我们可以在初始化中将非静态类成员分配给静态变量吗?
- 这些语句是否等效(静态变量、常量变量和泛型)
- 程序如何知道静态变量是否需要初始化?
- 类外的静态变量实例化
- 无法解析静态变量
- 函数局部静态变量:从性能角度来看的优点/缺点
- 访问从 CPP 文件到其他头文件的静态变量