Coercive function parameter to match some rule

Is there a way to "force" a function parameter to follow some rule in C ++?
For example, suppose I want to write a function that calculates the nth derivative of a mathematical function. Suppose the function signature is:

double computeNthDerivative(double x, unsigned int n);


Now, let's say I want to prevent users from entering 0 for n. I could just use assert

or check for value and throw

exception if user input is 0.
But is there any other way to do things like this?

Edit: the conditions will be set at compile time, but the check must be done at runtime.


source to share

5 answers

class Policy {
    String myPolicy;
public :
    Policy(String regEx) : myPolicy(regEx) {

    void verify(int n) {
       regEx strtok , sprintf, blah, blah n

class Asserted {
    Policy policy;
    Asserted(Policy policy, int n) throw AAAHHHHH {


Then finally

Asserted assert = new Asserted(Policy("[1-9]", 8))
double computeNthDerivative(2.6, assert);




At compile time, you can disable use 0

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 function from being used 0

at runtime, it is 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




I think the best way here is to throw an exception. With the exceptions, even the title seems to suggest it.

There assert

is one important caveat when it comes to macros . If you use a macro assert

, the program will abort if the assertion fails. However, if you ever create a release build where the macro is installed NDEBUG

, all statements will be removedat compile time. This means that you cannot validate user input with this macro (because you have to build a release build).



The only rules you introduce. If the users are the ones you want to restrict, you should check what they give. The same goes for functions, however in your case what you showed as an example it is better to check the variable after cin (or whatever capacity you prefer) rather than checking it in the function itself. For this I would just go if n! = 0; your else break function;



So, if you're looking for a policy based solution, you can create a separate class that accepts a defining regex (or whatever you define as a policy) and input, in this case n

, which is then used as input to your function.



All Articles