有没有办法可以创建一个带有int模板参数的函数,并且如果传递给函数的值小于10,那么该函数会产生编译时错误?
以下代码不起作用,但它显示了我想要完成的任务:
template <int number1>
void reportErrorIfLessthan10()
{
#if(number1 < 10)
#error the number is less than 10
#endif
}
int maint(int argc,char**argv)
{
reportErrorIfLessthan10<5>();//report an error!
reportErrorIfLessthan10<12>();//ok
return 0;
}
解决方法
如果你不想要
Boost C++ Libraries魔法并想要裸骨……
template<bool> class static_check
{
};
template<> class static_check<false>
{
private: static_check();
};
#define StaticAssert(test) static_check<(test) != 0>()
然后使用StaticAssert.这对我来说是一个#define,因为我的代码需要在许多环境中运行,其中C不适用于模板,我需要将其备份到运行时断言.
总结
以上是DEVMAX为你收集整理的C元编程 – 在代码中生成错误全部内容。
如果觉得DEVMAX网站内容还不错,欢迎将DEVMAX网站推荐给好友。