Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send array of 2 integers as argument

I am trying to make this C++ code more abstract, easier to see and understand, and less space occupier. It is a function that takes a string and two integers for a size and a position.

HWND CreateButon(string Title, const int[2] Size, const int[2] Position) {
    // Create the control, assign title, size and position
    // Return HWND
}

HWND MyButton = CreateButton("Button1", [100, 20], [10, 10]);

I know the last one is wrong. I just wrote it that way so you can see what I mean. I would like to send the size and position values directly as an argument. I could use structs but they must be declared before. The same with some other kind of variables. I just want to send them in the arguments as groups of two integers and I wonder if there's a workaround for it. More than anything else it's just for the sake of having it compact and simple.

like image 342
ali Avatar asked Nov 17 '25 16:11

ali


1 Answers

You could pass a pair instead of an array:

HWND CreateButton(string Title, std::pair<int,int> Size, std::pair<int,int> Position);

CreateButton("Button1", {100, 20}, {10,10});                            // C++11
CreateButton("Button1", std::make_pair(100,20), std::make_pair(10,10)); // C++03

Alternatively, in C++11 only, you could pass std::array<int,2>. That needs slightly stranger aggregate initialisation {{100, 20}}, but means you won't lose ability to index it using [].

Personally, I'd probably prefer to define the structs you describe; that would give more type safety and self-documentation, which I tend to value more than compactness. In fact, I might even go as far as giving them an explicit constructor (rather than allowing list initialistion) so you have to use "named arguments":

CreateButton("Button1", Size(100,20), Position(10,10));
like image 61
Mike Seymour Avatar answered Nov 20 '25 05:11

Mike Seymour



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!