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

Bri*_*ndy 6 c++ templates metaprogramming

有没有办法可以创建一个带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;
}
Run Code Online (Sandbox Code Playgroud)

Joe*_*Joe 7

如果你不想让Boost C++ Libraries变得神奇并且想要骨干......

template<bool> class static_check
{
};

template<> class static_check<false>
{
private: static_check();
};

#define StaticAssert(test) static_check<(test) != 0>()
Run Code Online (Sandbox Code Playgroud)

然后使用StaticAssert.这对我来说是一个#define,因为我的代码需要在很多C++不适合模板的环境中运行,我需要将它备份到运行时断言.:(

此外,不是最好的错误消息.