I have two methods:
ind addFilter(ind column, const QString & condition);
ind addFilter(ind column, bool condition);
When I use this construction gcc choose second method (with bool condition
)
filters->addFilter(familyNameInd, "М*");
Why std::string
convert to bool instead of QString? Or can I specify all string literals to be QString at compilation?
According to the C++ Standard (13.3.3.2 Ranking implicit conversion sequences)
2 When comparing the basic forms of implicit conversion sequences (as defined in 13.3.3.1) — a standard conversion sequence (13.3.3.1.1) is a better conversion sequence than a user-defined conversion sequence or an ellipsis conversion sequence, and ...
Relative to your example converting to bool is a standard implicit conversion. So it s better than user-defined conversion using a conversion constructor. So if you want that the overloaded function with parameter of type const QString &
would be called you have to specify explicitly the conversion from the string literal to a temporary object of type QString:
QString( "М*" )`.
"M*" is a const char* which is convertible to a bool due to implicit conversion rules. The implicit conversion will be chosen over the QString class.
You are going to have to call the function like this:
filters->addFilter(familyNameInd, QString("М*"));
To avoid an unnecessary copy of the QString, consider using the QStringLiteral macro as well:
filters->addFilter(familyNameInd, QStringLiteral("М*"));
First of all, your code is broken. There is no such an argument and return type as ind
. I will assume that you meant int
.
Secondly, POD types have precedence over custom types in C++ when it comes to implicit conversion.
Why std::string convert to bool instead of QString?
I do not know why you think it would be std::string
. It simply is not, not even in C++. It is the good old const char[X] where X happens to be three in your case (two letters + terminating nil).
Or can I specify all string literals to be QString at compilation?
No, but you ought to use this in any case when dealing with string literals in Qt regardless of this situation:
filters->addFilter(familyNameInd, QStringLiteral("М*"));
For raw string literals like this, please do not use the QString
contructor. It is pointless. Therefore, you would be writing something like this:
#include <QString>
#include <QDebug>
int addFilter(int column, const QString & condition) { qDebug() << "Test 1"; }
int addFilter(int column, bool condition) { qDebug() << "Test 2"; }
int main()
{
addFilter(0, QStringLiteral("foo"));
return 0;
}
TEMPLATE = app
TARGET = main
QT = core
SOURCES += main.cpp
qmake && make && ./main
Test 1
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.