AJM*_*eld 2 c++ templates overloading static-assert c++11
我正在尝试编写一个函数,如果使用编译时常量参数调用它将触发编译时错误,如果参数的值与a不匹配static_assert,但仍然可以在运行时使用计算值调用.
有点像这样:
template<int N> void f(N){
static_assert(N == 5, "N can only be 5.");
do_something_with(N);
}
void f(int N){
if(N == 5){
do_something_with(N);
}
}
volatile int five = 5;
volatile int six = 6;
int main() {
f(5); //ok
f(6); //compile-time error
f(five); //ok
f(six); //run-time abort
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我怎样才能做到这一点?
此外,如果可能的话,我希望能够保留简单的f(something)语法,因为此代码适用于不熟悉模板语法的初学者程序员可以使用的库.
我能想象的最好的是一个constexpr抛出异常的函数.
如果在编译时执行,则throw导致编译错误; 如果在运行时执行,则抛出异常
有点喜欢
#include <stdexcept>
constexpr int checkGreaterThanZero (int val)
{ return val > 0 ? val : throw std::domain_error("!"); }
int main()
{
// constexpr int ic { checkGreaterThanZero(-1) }; // compile error
int ir { checkGreaterThanZero(-1) }; // runtime error
}
Run Code Online (Sandbox Code Playgroud)
- 编辑 -
正如yuri kilocheck指出的那样,你可以打电话给std::abort(); 通过例子
constexpr int checkGreaterThanZero (int val)
{ return val > 0 ? val : (std::abort(), 0); }
Run Code Online (Sandbox Code Playgroud)