c++ - 如果 compile-time-constant 参数错误,则生成编译时错误

标签 c++ c++11 templates overloading static-assert

我正在尝试编写一个函数,如果使用编译时常量参数调用它,如果参数的值与 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) 语法,因为这段代码是为一个库设计的,不熟悉的初学者应该可以使用它使用模板语法。

最佳答案

我能想到的最好的是一个抛出异常的 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
 }

-- 编辑 --

正如 yuri kilocheck 所指出的,您可以调用 std::abort() 而不是抛出异常;举例说明

constexpr int checkGreaterThanZero (int val)
 { return val > 0 ? val : (std::abort(), 0); }

关于c++ - 如果 compile-time-constant 参数错误,则生成编译时错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42424661/

相关文章:

c++:内存中静态库的多个拷贝

c++ - 类中数据大小的整数模板参数

c++ - 运行 Gtkmm 对话框失败

c++ - 为什么我的数据元素被复制而不是 move ?

c++ - union 不能在类型说明符中定义

c++ - 无法在初始化时转换匿名枚举

c++ - 仅在 Visual Studio 外部运行时才能找到文本文件

c++11 - C++ 中的双 & 符号。 (第一个声明在 func 参数上,第二个声明在变量之前)

c++ - 派生类的模板特化问题

HTML 电子邮件模板 Mailchimp、Outlook 和 Gmail 中的 CSS 问题