Reputation: 143
Here i want to call world
function from class Hello
with macro MPRINT()
but it doesn't recognize the macro syntax:
#include <windows.h>
#include <iostream>
#include <string.h>
using namespace std;
// first try
#define MPRINT(text) \
[]() -> Hello::world(#text)\
}()
// second try
#define MPRINT(text) \
Hello obj; \
obj.world(text);
class Hello
{
public:
string world(string inp);
};
string Hello::world(string inp) {
return inp + "|test";
}
int main()
{
string test1 = MPRINT("blahblah"); // error "type name is not allowed"
cout << MPRINT("blahblah"); // error "type name is not allowed"
return 0;
}
Upvotes: 0
Views: 709
Reputation: 60440
In your first attempt, you are trying to use Hello::world
, but this is not the correct syntax for calling a non-static member function.
In your second attempt, using MPRINT
would result in:
string test1 = Hello obj; obj.world(text); ;
which is also clearly invalid.
You could write the macro like this:
#define MPRINT(text) \
[] { \
Hello obj; \
return obj.world(#text); \
}()
Here's a demo.
That being said, I strongly suggest that you don't use macros for this sort of thing. The following function works perfectly well:
auto MPRINT(std::string text)
{
Hello obj;
return obj.world(text);
};
Here's a demo.
Upvotes: 3