Backstory (You can skip)
In trying to form the question as best I could, I was informed that the second set of parentheses for a #define
macro is not a return
like I thought it was, but actually a cast
. To that, as far as I know; the only way to capture the expression text is by using the #define
macro. The tricky part, perhaps impossible, is to capture the explicit type
's text, but what do I know?
Also; the reason I specified this to Qt and not just C++/gcc, is that I figure that a solution might involve a class like QVariant
which adds some polymorphism, however this is not ideal as it is difficult to distinguish between some various basic types, like int
vs bool
.
What I am hoping to achieve
Basically, I want a wrapper, I am guessing a macro, which will log the nested expression text, its value, and return its exact nested's type (no implicit conversions).
For example:
/* Basic Definitions */
// log() could be overloaded or use different namespaces if need be
// and have preproccessor directives choose the appropriate one,
// although I dont suspect that is possible.
QVariant log(QString expression, QVariant value, QString type);
// TYPE is placeholder code. Normally I specify a real type like "bool"
// I am hoping TYPE can represent the captured type text
// #EXPR returns the text of the expression, in case you didnt know
#define LOG(EXPR)(TYPE)(log(#EXPR, EXPR, TYPE));
In this sample code:
/* Sample Code */
QString path;
if (LOG(path.isEmpty())) {
path = LOG(QDir::currentPath());
}
The wrapper LOG
should log the following:
Expression: "path.isEmpty()" Value: "True" Type: "bool"
Expression: "QDir::currentPath()" Value: "/home/akiva/Programming/" Type: "QString"
Id like to see if I could achieve this without having to resort to multiple macro namespaces, like this:
/* Bad solution because I dont want to have to specify LOG_bool & LOG_QString */
QString path;
if (LOG_bool(path.isEmpty())) {
path = LOG_QString(QDir::currentPath());
}
and I figure one possible solution would reveal itself if I could capture the text of the type, but I am open to all solutions, be it Macros, Templates, Functions or what have you.
My minimum requirements are:
- Needs to capture the expression text. (I know how to do that with macros)
- Only require one wrapper namespace, because I dont want to accidentally use the wrong wrapper corrupting my logs or which may cause an implicit conversion, thus potentially changing the intended behaviour of the wrapped expression.
- The wrapper must return/cast the exact type of the nested expression, or in other words, not affect the exact intended behaviour of the nested expression.
Being able to actually log the type, like Type: "bool"
& Type: "QString"
would be nice, but is not required.
I hope this all makes sense. Thanks.