强制函数参数匹配某些规则

Zou*_*uch 3 c++ c++11

有没有办法"强制"一个函数参数来遵循C++中的一些规则?
为了举例,我想写一个计算数学函数的n阶导数的函数.假设函数的签名是这样的:

double computeNthDerivative(double x, unsigned int n);
Run Code Online (Sandbox Code Playgroud)

现在,假设我想禁止用户为n输入0.如果用户输入为0,我可以使用assert或测试值和throw异常.
但有没有其他方法可以做这种事情?

编辑:条件将在编译时设置,但检查必须在运行时完成.

R S*_*ahu 5

您可以0使用模板阻止在编译时使用.

template <int N>
double computeNthDerivative(double x)
{
  // Disallow its usage for 0 by using static_assert.
  static_assert(N != 0, "Using 0 is not allowed");

  // Implement the logic for non-zero N
}
Run Code Online (Sandbox Code Playgroud)

要防止0在运行时使用该函数,最好抛出异常.

double computeNthDerivative(double x, unsinged int n)
{
   if ( n == 0 )
   {
      throw std::out_of_range("Use of the function for n = 0 is not allowed.");
   }

   // Implement the logic for non-zero n
}
Run Code Online (Sandbox Code Playgroud)