C ++ using struct arguments for functions instead of multiple arguments?

Does anyone think there are advantages to using a class or structure to pass arguments?

How instead

f(int,float,string)

Have

f(Args)

Where Argsthere is structa int, float, stringmembers.

The advantage is that it is easy to create several default parameters and you do not need to change the function signature when adding new arguments.

+4
source share
6 answers

Does anyone think there are advantages to using a class or structure to pass arguments?

Yes, I think there are many advantages.

, struct class.

struct, ( ) .

+1

.

, () , .

, /.

.

+1

, : . , foo(A, B) ( A B). foo(b, a) , ..

- Context. ++ 11 , " superset " .

+1

, / , .

:

struct Foo
{
   char const* source;
   char* destination;
};


Foo strcpy(Foo foo);

:

struct Point
{
   int x;
   int y;
};


int distanceFromOrigin(Point p) { ... }

int distanceFromOrigin(int x, int y) { ... }
+1

. , . , , , - , - const . , struct, . .

+1

, - . , , , , struct, -, .

Take, for example, the Direct3D11 function ID3D11Device :: CreateDepthStencilState : the transfer is const D3D11_DEPTH_STENCIL_DESC *pDepthStencilDescmuch clearer than the request for the entire required parameter.

Also, think about variability: you do not need to change this method signature, but only the underlying data structure during refactoring. I found this especially useful when working together, when someone sets the interface and someone else needs to implement it.

+1
source

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


All Articles