简体   繁体   中英

Is it possible to pass an “unnamed” variable to a function?

Let's say there is the following function:

void SetTheSize(const SIZE *size) { ... }

Is there any way to call that function without specifying the SIZE variable? eg,

SetTheSize((const SIZE*)&{10, 10});

edit: I should had mentioned that the SIZE is a struct, without SIZE(int, int) constructor.

No, only thing nearest in C++ is to do like this:

void SetTheSize(const SIZE& size); //Change the pointer to const reference

And call it using an unnamed temporary variable: SetTheSize(SIZE(10,10));

SetTheSize(&SIZE{10, 10}); would "work" with the improved initialization syntax in C++0x.

It "only" deserves a warning: taking address of a temporary.

Legal things to do would be to bind the temporary to references:

void SetTheSize(SIZE&&);

or

void SetTheSize(const Size&);

with usage

SetTheSize(Size{10, 10});

You can't do it via a pointer, although you can pass a temporary via a const reference. And you can't create arrays like that (if that's what your syntax is trying to do). So, no.

None of the answers so far have been pedantic, and somebody's got to do it. It's actually really quite easy:

void SetTheSize(const SIZE *size);
SIZE const newSize(10, 10);
SetTheSize(&newSize);

The variable being passed to SetTheSize is indeed an unnamed temporary. It is the result of the expression &newSize and has type SIZE const* .

If you wanted the SIZE object itself to be an unnamed temporary, instead of the pointer passed to SetTheSize , that's possible too:

void SetTheSize(const SIZE *size);
SIZE const& newSize = SIZE(10, 10);
SetTheSize(&newSize);

Now newSize is a reference to an unnamed temporary variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM