将if语句放在编译期执行,可以用模板特化的方式实现。下面是调用代码:
// test if cout << "test if" << endl; If<false>::Run();
输出结果为:
test if it‘s false
模板类的实现如下:
template<bool condition>
class If {
public:
static inline void Run() {
cout << "it‘s true" << endl;
}
};
template<>
class If<false> {
public:
static inline void Run() {
cout << "it‘s false" << endl;
}
};原文地址:http://blog.csdn.net/csfreebird/article/details/44888887