Reputation: 105
I develop with QtFramework in c++. I encountered this converting method that is static_cast<void (QTcpSocket::*)(QAbstractSocket::SocketError)>
(&QAbstractSocket::error)
. But I have not understand what is it mean?
Upvotes: 2
Views: 225
Reputation: 16341
static_cast<void (QTcpSocket::*)(QAbstractSocket::SocketError)> (&QAbstractSocket::error)
where:
&QAbstractSocket::error
- is the address of the function named error(...)
;
And it is casting it to void (QTcpSocket::*)(QAbstractSocket::SocketError)
- which is a pointer to a member (of QTcpSocket) function that takes a parameter QAbstractSocket::SocketError
and returns void
.
So we are casting from address of a function which is a member of QAbstractSocket (perhaps a base class) to a function pointer which is a member of QTcpSocket (perhaps the derived class).
Note
As talamaki explains really nicely the reason for this (i.e. to pick the correct function during a connect(...); An alternative is to use the older Qt connect() style which you can explicitly choose the correct function at the cost of losing compiler-time errors if you get it wrong. I often think this is clearer (for example this question would probably not need to be asked). Here is an example:
// Here we can explicitly choose the correct function,
// and its clear to any reader what is going on.
connect(pTcpSocket, SIGNAL(error(QAbstractSocket::SocketError)),
this, SLOT(errorHandler(QAbstractSocket::SocketError)));
Upvotes: 1
Reputation: 5472
QTcpSocket inherits from the base class QAbstractSocket. There is a method SocketError error()
and a signal void error(QAbstractSocket::SocketError socketError)
in QAbstractSocket, i.e. with the same name.
In the presence of overloads the address of the name of the function in itself is ambiguous. You can use static_cast<>()
to specify which function to use according to the function signature implied by the function pointer type.
The cast in your question selects the signal because void (QTcpSocket::*)(QAbstractSocket::SocketError)
is a pointer to a function type in QTcpSocket which returns void
and takes a parameter QAbstractSocket::SocketError
.
For example to connect to QAbstractSocket::error
signal using the function pointer syntax, you must specify the signal type in a static cast.
Upvotes: 2