C元编程 – 在代码中生成错误

前端之家收集整理的这篇文章主要介绍了C元编程 – 在代码中生成错误前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
有没有办法可以创建一个带有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不适用于模板,我需要将其备份到运行时断言. 原文链接:https://www.f2er.com/c/116088.html

猜你在找的C&C++相关文章