【发布时间】:2017-02-23 19:37:41
【问题描述】:
我正在尝试编写一个函数,如果使用编译时常量参数调用,如果参数的值与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;
}
我该怎么做?
另外,如果可能的话,我希望能够保留简单的f(something) 语法,因为此代码适用于不熟悉模板语法的初学者程序员应该可以使用的库。
【问题讨论】:
-
无法推导出作为参数传递给函数的值,因此
template<int N> void f(N){行不正确 -
编译时或运行时。你必须选择(或做两个功能)。
-
有没有办法使用
constexpr而不是模板的东西? -
@BlackMoses 函数能够执行运行时错误/异常并不是绝对必要的,但它需要能够使用编译时不可用的值来调用它。
标签: c++ c++11 templates overloading static-assert