For example, I have a class
struct A
{
A(int i, double d) {...}
};
and a function with an argument A
void f(A a);
I can call the function by
f( { 1, 3.14 } );
If the function has an argument A*
void g(A* a);
How to make it call like
g( my_new{1, 3.14} ); // Note: no type A is shown here.
Or how to derive the type A here?
You can't take an address of a temporary with &:
g(&({1, 3.14}));
as per:
§5.3.1/3
The result of the unary & operator is a pointer to its operand. The operand shall be an lvalue or a qualified-id.
(emphasis mine)
For example, you can use a function to extract the pointer to the temporary object:
A* fn(A&& a) {
return std::addressof(a);
}
and use it as:
g(fn({1, 4.0}));
Note that std::addressof is necessary to avoid possible operator& overloading for the class A.
You could also extract it via a member function of the class A and probably many other ways.
Why the sudden opinion change? Well, I've discussed it with other C++ haters and apparently it is possible and perfectly legal.
I'd recommend for g to take a const reference instead:
void g(const A& a);
and then:
g({1, 3.14});
will work fine (assuming, of course, that the constructor is not explicit).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With