How to protect functions from arguments passed in the wrong order?

Let's say I have C ++ - a function that looks like this:

double myfunction(double a, double b) {
    // do something
}

What I then call this:

double a = 1.0;
double b = 2.0;
double good_r = myfunction(a, b);
double bad_r = myfunction(b, a); // compiles fine

I would like to make sure that aand bnever appear in the wrong order. What is the best way to provide this in C ++?

Other languages ​​allow named parameters, for example:

double good_r = myfunction(a=a, b=b);
double bad_r = myfunction(a=b, b=a); // mistake immediately obvious
double bad_r = myfunction(b=b, a=a); // compiles fine

Or maybe the problem can be partially solved using types, i.e.

double my_type_safe_function(a_type a, b_type b) {
    // do something
}
a_type a = 1.0;
b_type b = 2.0;
double good_r = myfunction(a, b);
double bad_r = myfunction(b, a); // compilation error

EDIT: , " ". , a b . , height width. , . , (.. ). , "" . , , (width, height), , , (height, width). , . , 6 .

, , , (.. - ).

+4
4

:

struct typeAB {float a; float b; };

double myfunction(typeAB p) {
// do something
  return p.a - p.b;
}

int main()
{
  typeAB param;
  param.a = 1.0;
  param.b = 2.0;
  float result = myfunction(param);
  return 0;
}

, , , :)

+3

, "" , .

- ( , ):

#define SAFE 0

#if SAFE
#define NEWTYPE(name, type) \
    struct name { \
       type x; \
       explicit name(type x_) : x(x_) {}\
       operator type() const { return x; }\
    }
#else
#define NEWTYPE(name, type) typedef type name
#endif

NEWTYPE(Width, double);
NEWTYPE(Height, double);

double area(Width w, Height h)
{
    return w * h;
}

int main()
{
    cout << area(Width(10), Height(20)) << endl;

    // This line says 'Could not convert from Height to Width' in g++ if SAFE is on.
    cout << area(Height(10), Width(20)) << endl; 
}
+2

, , .

. :

class MyfunctionBuilder {
  MyFunctionBuilder & paramA(double value);
  MyFunctionBuilder & paramB(double value);
  double execute();
  (...)
}

:

double good_r = MyFunctionBuilder().paramA(a).paramB(b).execute();

!

+1

" "?

double myfunction(double a, double b) {
    // do something
}

double a = 1.0;
double b = 2.0;
double good_r = myfunction(a, b);
double bad_r = myfunction(b, a);

, ? , "quapr" "moo" "a" "b"? , , .

. -, , .

float getTax( float price, float taxPercentage )

float getTax( float a, float b )

-, :

float divide( float dividend, float divisor )
{
    if( divisor == 0 )
    {
         throw "omg!";
    }
}

, , , , .

0

Source: https://habr.com/ru/post/1537709/


All Articles