Answer the question
In order to leave comments, you need to log in
How to count and convert to string in C++ using preprocessor?
Tell me how in C ++ using macros, first calculate the formula, and convert the result to a string? For example, there is
#define A 2
#define B 3
#define MUL(x,y) (x*y)
#define STR(x) #x
How do I get the string "6"? Naturally STR(MUL(A,B)) doesn't work.
Answer the question
In order to leave comments, you need to log in
No way - the preprocessor, in principle, does not perform arithmetic operations. Is it possible to stir up some lambda calculus ...
Hm, why not?
#include <boost/preprocessor.hpp>
BOOST_PP_STRINGIZE(BOOST_PP_MUL(A, B))
As you have already been pointed out above, macros are what follows from their name - macro substitution. What you want to achieve, in older editions of C++, is decided by templates. In the new one - constexpr.
The macros themselves don't evaluate, of course, but the value 3 + 3 is still calculated at compile time. That's just the line where 6 is written, you can't make it out of it.
Choose what you need
#include <QtCore>
#include <iostream>
using namespace std;
# define MULT(VAL1,VAL2) ((VAL1)*(VAL2))
# define AS_STR(NUM_VAL) ( QString("")+#NUM_VAL )
# define AS_STR_VAL(NUM_VAL) ( QString().sprintf("%d",NUM_VAL) )
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
int i = MULT(1+2,1+1+1);
cout << "Variant 1: " << qPrintable(AS_STR(i)) << endl;
cout << "Variant 2: " << qPrintable(AS_STR(MULT(1+2,1+1+1))) << endl;
cout << "Variant 3: " << qPrintable(AS_STR_VAL(MULT(1+2,1+1+1))) << endl;
return a.exec();
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question