Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force function parameter to match some rule

Tags:

c++

c++11

Is there any way to "force" a function parameter to follow some rule in C++ ?
For the sake of example, let say I want to write a function which computes the n'th derivative of a mathematical function. Let suppose the signature of the function is this one :

double computeNthDerivative(double x, unsigned int n);

Now, let say I want to forbid users to input 0 for n. I could just use an assert or test the value and throw an exception if the user input is 0.
But is there any other way of doing this kind of stuff ?

Edit : Conditions would be set at compile time, but the check must be done at the run-time.

like image 566
cmourglia Avatar asked Jun 23 '26 18:06

cmourglia


1 Answers

You can prevent the use of 0 at compile time, using templates.

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
}

To prevent the use of the function for 0 at run time, it's best to throw an exception.

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
}
like image 101
R Sahu Avatar answered Jun 25 '26 12:06

R Sahu