Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Qt 5: const char * QString cast

In Qt 4 it is possible to automatically cast a QString to a "const char *", e.g. I could pass a QString to a function that expected a "const char *".

void myFunction(const char *parameter);

QString myString;
myFunction(myString); //works in QT4

In Qt 5 I would however get an "error C2440: 'type cast' : cannot convert from 'QString' to 'const char *'" (that is the Visual C++ 2008 compiler, other compilers would throw something similar). If I understand the documentation correctly, it is because the Qt 3 compatibility layer is not included anymore in QT5.

Of course, I could change the function call from

myFunction(myString); 

to

myFunction(myString.toLatin1().data());

However, I have a huge code base that compiles fine with Qt 4 and I would really like to have my old code compile with Qt 5 without modifying it. Is there any way to achieve this?

like image 459
user3640262 Avatar asked Nov 01 '22 23:11

user3640262


1 Answers

You could create a macro or inline function for your purpose to minimize the changes, but since that would also require a grep alike operation, there is not much difference.

#define QString2charp(myString) myString.toLatin1().data()

or

inline char* QString2charp (const QString &myString)
{
    return myString.toLatin1().data();
}

and then:

myFunction(QString2charp(myString));

BUT

of course, in an ideal world, it would be nice if your "myFunction" could get an overload expecting a QString argument.

void myFunction(const char *parameter);
void myFunction(QString parameter);

and then the overload would be implemented like this:

void myFunction(const QString &parameter)
{
    myFunction(myString.toLatin1().data());
}

of course, this would require the constructor being explicit so that no implicit conversion can happen, otherwise the compiler will complain about ambiguity in presence of both when trying to pass const char*, but if you always use QString, it should just work with Qt 5.

This is somewhat equal to rewriting the original function to a different signature expecting QString though because unfortunately the corresponding constructor is not explicit. I imagine that was not changed in Qt 5 for compatibility as it would have broken too much code.

As you can see, you do not need to change anything in your code this way, other than adding a one-liner overload. It is neat, isn't it?

like image 186
lpapp Avatar answered Nov 15 '22 05:11

lpapp