12

I am trying the following code:

std::thread t(&(Transmitter::sender), this, some_variables);

where sender is a member function of the same class from whose method the above line is being called.

I get the warning:

Transmitter.h: In member function 'int Transmitter::transmit_streams(std::vector<std::vector<single_stream_record> >, int, Receiver&)':
Transmitter.h:81:44: error: ISO C++ forbids taking the address of an unqualified or parenthesized non-static member function to form a pointer to member function.  Say '&Transmitter::sender' [-fpermissive]

though it compiles and runs fine. How can I remove this warning.

My g++ is 4.6.3 and I compile the code with -std=c++0x.

mrflash818
  • 930
  • 13
  • 24
AbbasFaisal
  • 1,428
  • 2
  • 18
  • 21

1 Answers1

19

The error message is very clear.

ISO C++ forbids taking the address of an unqualified or parenthesized non-static member function to form a pointer to member function. Say '&Transmitter::sender' [-fpermissive]

From expr.unary.op

A pointer to member is only formed when an explicit & is used and its operand is a qualified-id not enclosed in parentheses. [ Note: That is, the expression &(qualified-id), where the qualified-id is enclosed in parentheses, does not form an expression of type “pointer to member”. Neither does qualified-id, because there is no implicit conversion from a qualified-id for a non-static member function to the type “pointer to member function” as there is from an lvalue of function type to the type “pointer to function” ([conv.func]). Nor is &unqualified-id a pointer to member, even within the scope of the unqualified-id's class. — end note ]

You need to use:

    std::thread t(&Transmitter::sender, this, some_variables);

See this demo

Danh
  • 5,916
  • 7
  • 30
  • 45
  • 1
    Yes, your code seems to work. Though being new to C++, I can't understand why. I mean, the difference between yours and mine is only that yours is lacking parenthesis around Transmitter::sender. – AbbasFaisal Nov 26 '16 at 15:23
  • 1
    @AbbasFaisal Because the ISO C++ said so, see my edit – Danh Nov 26 '16 at 15:28
  • 2
    This answer has an example that explains why it was done this way - https://stackoverflow.com/a/7138582/1000551 – Vadim Kotov May 15 '18 at 23:10