Token-pasting operator (##) is eating spaces in my C++ macro - c++

I was having trouble with the following macro, and I found out that the token-pasting operator (##) is eating the space between static and the return type:
#define MY_FUNCTION(aReturnType) static ##aReturnType MyFunction() { }
So the preprocessor was turning this:
MY_FUNCTION(bool)
into this:
staticbool MyFunction() { }
which caused weird compilation errors.
I came up with the idea of putting parentheses around the static keyword:
// This works but is kind of weird
#define MY_FUNCTION(aReturnType) (static) ##aReturnType MyFunction() { }
Are there any better solutions?

I think that your problem is that you don't want to use token pasting here. If you change the macro to
#define MY_FUNCTION(aReturnType) static aReturnType MyFunction() { }
Then if you write
MY_FUNCTION(bool)
it will expand out into
static bool MyFunction() { }
I am assuming that this is what you want to do, since I can't see what you're trying to paste the aReturnType argument to the macro onto.
Hope this helps!

As it should do? You told it to paste together static and bool. If you don't want that and you want static bool instead, then don't paste them together?

Related

Met c++ code " #define ELEMENT(TYPE, FIELD)"

#define ELEMENT(TYPE, FIELD)\
bool get##FIELD(TYPE *field) const throw()\
{ \
return x_->get##FIELD(y_, field);\
} \
I never met code like this before.
First, why do we put code in #define, is it a macro? So, I can use ELEMENT() later in other places?
Second, what is ##? What I can find online is "The ## operator takes two separate tokens and pastes them together to form a single token. The resulting token could be a variable name, class name or any other identifier."
Could someone tell me how I should know what this kind of code works?
Yes, ELEMENT() is a preprocessor macro, which is just a fancy way to replace one piece of text with another piece of text before the compiler is invoked. At the site where a macro is invoked, it is replaced with the text content of the macro. If the macro has parameters, each parameter is replaced with the text that the caller passed in to the macro.
In this case, the TYPE parameter is being used as-is within the macro text, whereas the FIELD parameter is being concatenated with get via ## concatenation to produce a new token identifier get<FIELD>.
ELEMENT() can be used like this, for example:
class MyClass
{
ELEMENT(int, IntValue) // TYPE=int, FIELD=IntValue
ELEMENT(string, StrData) // TYPE=string, FIELD=StrData
// and so on ...
};
Which will be expanded by the preprocessor to this code, which is what the compiler actually sees:
class MyClass
{
bool getIntValue(int *field) const throw()
{
return x_->getIntValue(y_, field);
}
bool getStrData(string *field) const throw()
{
return x_->getStrData(y_, field);
}
// and so on ...
};
I'm sorry to tell you, someone tried to be clever.
#define is used to textually replace one piece of text with another. The 2 arguments can be passed as a kind of arguments. Normally, such an argument is a token. However, thanks to ##, one can do token concatenation.
Let's take an example: ELEMENT(int, Cost);
This will result in the following code being injected:
bool getCost(int *field) const throw()
...
So as you can see, int is kept as token, while Cost is glued together into getCost.
I hope you found this in legacy code, cause using the preprocessor is considered bad coding in C++. The language hasn't been able to get rid of most usages. However they are providing alternatives to most common usages.
The #include and header guards have gotten replacements with the C++20 modules proposal.

C++ Macro definition including dot?

I have some C++ code that I can't change, only by changing header files. I have the code and can compile it.
The issue is that I have a function pointer defined something like this (function pointer is kind of irrelevant to what I want to do):
foo.bar();
I would like change that with a macro or something to:
#define foo.bar() FunCall()
The issue as I understand is that it is not possible to use dots in a macro, is there any other way?
Edit:
A bit more info. The code I get is intended to run a single instance, however I'm wrapping the code to run multiple instances in a class. That gives some headaches I'm trying to over come.
What I'm trying is either to use a macro and some inline functions or a complete third way:
void function()
{
foo.bar();
}
I need some code that could make above equivalent to:
void class::function()
{
EventFuncTypedef f = foo.bar;
(this->*f)();
}
Or
void class::function()
{
class::FunCall();
}
The code above all work the issue is to try get option 1 or 2 executed by the original code.
with a macro and an helper:
struct FunCaller {
static auto bar() {FunCall();}
};
#define foo FunCaller{}

C++ macro expansion to function body

I would like to be able to write a macro CONDITIONALFUNCTION so that
CONDITIONALFUNCTION( FunctionName )
{
ConditionalExpression()
}
expands to
bool FunctionName( const Arguments& args )
{
return ConditionalExpression();
}
Is this even possible?
The closest I can find on SO is this thread:
Possible to define a function-like macro with a variable body?
except unlike in that thread, I have the additional requirement that the "body" within the braces is not a complete valid C++ statement, but rather an expression to be wrapped (effectively) in an 'if' statement.
Please assume I already know this may be impossible, and is almost surely stupid and evil :)
I'm going to assume you've got a good reason for using macros in the first place...
It's not possible with the syntax you've given with the question.
The closest workable macro syntax is:
#define CONDITIONALEXPRESSION(f, c) \
bool f( const Arguments& args ) \
{ return c; }
CONDITIONALEXPRESSION(FunctionName, ConditionalExpression())
This will expand to the same as the expanded function in the question
Is there any reason why the function body must be defined in the macro? In Microsoft C++, macros like ASSERT() define the actual function separately and then just reference it from the macro.
So the function is always defined but the macro is either equal to calling the function or nothing at all.
Aside from that, for C++ I'd probably use an inline function.
je4d already provided one alternative. I over some other variation:
#define CONDITIONALEXPRESSION(f) \
bool f( const Arguments& args )
#define CONDITIONALRETURN(c) \
return (c)
CONDITIONALEXPRESSION(FunctionName)
{
CONDITIONALRETURN(ConditionalExpression())
}

Is it possible to treat macro's arguments as regular expressions?

Suppose I have a C++ macro CATCH to replace the catch statement and that macro receive as parameter a variable-declaration regular expression, like <type_name> [*] <var_name> or something like that. Is there a way to recognize those "fields" and use them in the macro definition?
For instance:
#define CATCH(var_declaration) <var_type> <var_name> = (<var_type>) exception_object;
Would work just like:
#define CATCH(var_type, var_name) var_type var_name = (var_type) exception_object;
As questioned, I'm using g++.
You can't do it with just macros, but you can be clever with some helper code.
template<typename ExceptionObjectType>
struct ExceptionObjectWrapper {
ExceptionObjectType& m_unwrapped;
ExceptionObjectWrapper(ExceptionObjectType& unwrapped)
: m_unwrapped(unwrapped) {}
template<typename CastType>
operator CastType() { return (CastType)m_wrapped; }
};
template<typename T>
ExceptionObjectWrapper<T> make_execption_obj_wrapper(T& eobj) {
return ExceptionObjectWrapper<T>(eobj);
}
#define CATCH(var_decl) var_decl = make_exception_obj_wrapper(exception_object);
With these definitions,
CATCH(Foo ex);
should work. I will admit to laziness in not testing this (in my defence, I don't have your exception object test with). If exception_object can only be one type, you can get rid of the ExceptionObjectType template parameter. Further more, if you can define the cast operators on the exception_object itself you can remove the wrappers altogether. I'm guessing exception_object is actually a void* or something though and your casting pointers.
What compiler are you using? I've never seen this done in the gcc preprocessor, but I can't say for sure that no preprocessor out there can implement this functionality.
What you could do however is run your script through something like sed to do your prepreprocessing so to speak before the preprocessor kicks in.
Hmmm... I'm just guessing, but why don't you try something like this : :)
#define CATCH(varType,varName) catch(varType& varName) { /* some code here */ }

Enum declaration inside a scope that is a parameter of a macro

I am trying to create a macro that takes a scope as a parameter.
I know, it is probably not a good thing etc etc.
I was trying this and got the problem that preprocessor looks for commas and parentheses... the problem is with enum.
How would I declare a enum inside a scope that is a parameter of a macro?
when the compiler see the comma between enum itens, it takes it as a separator.
If you are curious to know why I entered into this, is because I need to register my namespaces and classes, for namespaces I need to know when they are closed, so I was thinking to create a macro that initially calls a static function that register the namespace, encapsulate its contents and finally call a static function that removes the namespace from the registry.
With a macro it would be easier for the coder to do this and make sure he doesn't forget to remove the namespace in the end of the bracket.
Thanks,
Joe
EDIT:
I want a macro that accepts a scope as parameters:
#define MYMACRO(unkownscope) unknownscope
class MYMACRO({
// please, don't take this code seriously, it is just an example so you can understand my question
});
now, if I try:
#define MYMACRO(unkownscope) unknownscope
class MYMACRO({
enum {
anything = 1,
everything = 2
};
});
it won't compile because of the comma inside the enum, because the compiler thinks it is a separator of the macro. It doesn't happen with commas inside parentheses, example:
int a(){
int x = anyfunction(1, 2);
}
would compile normally because the comma is inside a double parentheses.
Sorry for not being able to explain earlier... my english is not that good and the words just keep skipping me =[
Ty for the answers!
Joe
It sounds like you are pushing the preprocessor beyond where it's willing to go. While it's not as elegant, how about breaking your macro in two (one pre- and one post-) and rather then passing a "scope" as parameter, you surround your scope with you pre- and post- macros.
So, if your macro looks something like:
SOMACRO({ ... });
You would instead do something like:
PRESOMACRO();
{ ... };
POSTSOMACRO();
#define SCOPED_STUFF(pre,post) pre; STUFF; post;
#define STUFF enum {a,b,c}
SCOPED_STUFF(a,b)
#undef STUFF
#define STUFF enum {q,r}
SCOPED_STUFF(c,d)
#undef STUFF
You are attempting to replicate RAII with a macro.
#define SCOPE(ns) NamespaceRegistrar _ns_rar(ns);
struct NamespaceRegistrar {
std::string _ns;
NamespaceRegistrar(const std::string& ns) : _ns(ns) { AcquireResource(_ns); }
~NamespaceRegistrar() { ReleaseResource(_ns); }
};
{
SCOPE("Foo")
// stuff
}
I have no idea what you are talking about with regard to enums.
You already noticed what the problem is, an article on boostpro.com sums the problem up.
There are work-arounds, but i'd go for utilizing Boost.Preprocessor.
Without knowing exactly what you're trying to achieve syntactically, something like this might be what you are looking for (edited to PP_SEQ):
#define MAKE_ENUM(Name, Seq) enum Name { BOOST_PP_SEQ_ENUM(Seq) }
MAKE_ENUM(foo, (a)(b)(c));