AnilJ
AnilJ

Reputation: 2121

error: lvalue required as unary ‘&’ operand

In my code, I am calling the function like this:

Simulator::Schedule (Seconds(seconds),
                     &HelloProtocol::sendScheduledInterest(seconds), this, seconds);

Here is the signature of the above function:

  /**
   * @param time the relative expiration time of the event.
   * @param mem_ptr member method pointer to invoke
   * @param obj the object on which to invoke the member method
   * @param a1 the first argument to pass to the invoked method
   * @returns an id for the scheduled event.
   */
  template <typename MEM, typename OBJ, typename T1>
  static EventId Schedule (Time const &time, MEM mem_ptr, OBJ obj, T1 a1);

And the definition of function sendScheduledInterest() is:

void
HelloProtocol::sendScheduledInterest(uint32_t seconds)
{
    //...
}

I am getting the following compilation error:

hello-protocol.cpp: In member function ‘void ns3::nlsr::HelloProtocol::scheduleInterest(uint32_t)’:
hello-protocol.cpp:58:60: error: lvalue required as unary ‘&’ operand

If I remove the & before the function call, it gives the following error instead:

hello-protocol.cpp: In member function ‘void ns3::nlsr::HelloProtocol::scheduleInterest(uint32_t)’:
hello-protocol.cpp:58:75: error: invalid use of void expression

Upvotes: 1

Views: 2478

Answers (2)

tahsmith
tahsmith

Reputation: 1723

You are taking the address of the return value of sendScheduledInterest instead of the address of the method itself. Remove the (seconds) bit.

It seems like you may be intending to bind the seconds value to the call to sendScheduledInterest

With the standard library this can be achieved like this:

change Schedule to

EventId Schedule(const Time&, std::function<void()>);

and then use it as

Schedule(Seconds(seconds), bind(&HelloProtocol::sendScheduledInterest, this, seconds));

Upvotes: 2

b4hand
b4hand

Reputation: 9770

HelloProtocol::sendScheduledInterest is a void function. That means it returns no value. You can neither invoke the address of operator (&) on the return value of a void function nor can you pass it as an argument to another function unless that type is also void, which could only happen if there are some templates involved.

It appears you actually intend to pass the function pointer as the argument like this:

Simulator::Schedule(
    Seconds(seconds),
    &HelloProtocol::sendScheduledInterest,
    this,
    seconds);

In both cases, the compiler is telling you exactly what the issue is.

In the first case, a void expression is not an lvalue. You can think of an lvalue as something that can be assigned to on the left hand side of an assignment statement. The address of operator (&) can only be applied to lvalues.

In the second case, you are trying to use a void expression where it is not allowed, namely as the argument to a function whose formal argument type is non-void.

Upvotes: 5

Related Questions