0

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.

1
  • 1
    Is this really what you want? C++ has much cleaner solutions available, where you do not depend on strings, such as polymorphism. One advantage is that you will get compile-time errors in case of a coding mistake, rather than runtime errors. And your IDE will like you for it. Commented May 8, 2017 at 6:47

2 Answers 2

2

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")
           ...
}
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.