Lemonbonbon
Lemonbonbon

Reputation: 738

c++ function arguments with MATLAB syntax?

Comming from MATLAB, I would like to know if there is a way to use function arguments in c++ like it is done in MALTAB. Here is an example to illustrate, what I am trying to use in c++:

draw('shape','circle','radius',5); // should draw a circle
draw('shape','square','width',3,'hight',4); // should draw a square

The function above is the same, but the function arguements differ. I would like to use this syntax in c++. Is there a good way to do this? Thanks.

Upvotes: 0

Views: 65

Answers (2)

Zizy Archer
Zizy Archer

Reputation: 1390

You can make c++ work exactly like MATLAB (see answer above), but it doesn't make too much sense. A very good indication for that is your test case itself:

draw('shape','square','width',3,'hight',4); // should draw a square

You misspelt height. In my usual code you would be getting (runtime) warning of "unknown specifier hight" and having 4 ignored in favor of default value or perhaps doing nothing. And this warning is here only because I bother writing it in otherwise block. A lot of coworkers' code doesn't, and would just silently use default value or not do anything.

Now try debugging that in the middle of a complicated find some elements on image function - you wouldn't easily figure out it is a simple typo in your call to draw function.

So, instead of making Matlab code in c++, you should write something like:

void MyDrawingFunct(Shape shape){
...}

void MyDrawingFunct(Curve curve){
...}

Where you would draw shapes you have defined (like square, circle etc), and another function for curves etc. Or, if you want to safeguard against say adding Ellipse to Shape and have it fail at runtime, you can have some more functions - ...(Square ...) etc.

The main benefit is that trying to call MyDrawingFunct with say Ellipsoid will immediately notify you of error (at compile time), while doing things your usual MATLAB way will have you wondering whether ellipsoid is not implemented or you just made a typo somewhere (like in your example). And you will hit that at runtime.

Upvotes: 2

FlKo
FlKo

Reputation: 845

You could try the following (albeit it's not really clear what your main intention is):

void MyDrawingFunc(const std::vector<std::string>& Arguments)
{
    auto& arg = Arguments[0];

    if (arg == "shape")
        DoShapeStuff(Arguments); // use Arguments[1...]
    else if (arg == "otherThing")
           ...
}

Upvotes: 2

Related Questions