C++ Macro definition including dot? - c++

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{}

Related

how use the '#define' define a macro to exectue mutiple method?

I develop a mac app using c++. I want to define the macro 'logi' corresponding to the call of two methods, so that method1() and method2() are being called. So I tried this:
#define logi method1 method2
It does not work. What is standard writing of this situation? thanks a lot!
At very first: If you can, avoid macros. If it is about calling two functions in a sequence, prefer defining an inline function instead:
inline void logi()
{
method1();
method2();
}
While inline just is a recommendation for the compiler – and it might choose not to do so – for such simple functions you won't find any compiler not following this recommendation (rather would the function be inlined even without keyword).
This approach is much safer – and anything you do wrong the compiler will show you right at the function definition.
If you insist on a macro: Best practice is letting it look like a function, if it behaves like such one, as in your case:
#define logi() do { method1(); method2(); } while(false)
The loop wrapping around makes this macro robust if used like a function somewhere in code, imagine it was used without like that:
if(someCondition)
logi();
Guess, method2 would get called unconditionally (well, another example showing why it's good practice always to place braces around branch and loop bodies...).
The colon is skipped deliberately, so the user is forced to place it, again making the macro behave like an ordinary function.
Be aware that for macros the pre-processor does nothing more than simple text replacement. So whatever you define, it must be valid C++ code (to be precise: the outcome, when the pre-processor is done, must be valid code). How would a macro look like, if you needed to pass arguments to your functions? Well, you need to include them in the macro definition, too:
#define logi(A1, A2, B1, B2, B3) do { method1(A1, A2); method2(B1, B2, B3) } while(false)
I guess you only forgot the ';' between the two functions. Therefore that the #define-macro only is a text-replacement in your code you need to 'end' the call of your function with a ';'.
But you might want to overthink using the #define-macro that way. It does not seem to make much sense to me to do it this way. See here on "when to use #define"
#include <iostream>
#define logi fun1(); fun2();
void fun1(void)
{
std::cout << "fun1 called\n";
}
void fun2(void)
{
std::cout << "fun2 called\n";
}
int main(void)
{
logi
return 0;
}

How to prohibit call of specific functions when using a certain macro

I have a macro defined more or less like this:
#define SOME_MACRO(Name) \
bool Function#Name()
This macro is often used with certain functions. Let's call one of them foo().
It is used in several files like this:
SOME_MACRO(Hello) {
//do stuff here
foo();
//do more stuff here
}
A new macro FOO_MACRO that calls foo was created. From now on, when people call SOME_MACRO, I don't want them to call foo() directly. Instead, I want them to make use of FOO_MACRO, which is called before and outside SOME_MACRO.
The only way I could think of was to create a lambda function named foo inside the calls to SOME_MACRO. The newly defined foo would then output errors when called.
SOME_MACRO(Hello) {
auto foo = [](){
//error
};
foo(); //should generate error
//do more stuff here
}
I don't actually know if this will compile but even if it works, I will have to do this one by one on every call of SOME_MACRO. It's exhausting and the code becomes repetitive.
One thing I did try was to change the SOME_MACRO definition into something like this:
#define SOME_MACRO(Name) \
lots of stuff here \
namespace {
void foo () {}
}
bool Function#Name()
If I do this, calling foo will generate a compile error due to ambiguity of the call. This accomplishes my goal of not letting people call the function. But the error might be confusing to others. I want to be able to create an error that lets them know "don't call foo! Use FOO_MACRO instead!".
Is there any other way to achieve this? If possible, I really don't want to use the ambiguous call error.
I'm writing this from memory so there might be syntax errors in the sample codes.
You could have conditional #include statements based on some macro. This would include the correct definition of your function.
Have you considered polymorphism instead? This is the usual c++ answer to c macro ugliness

C++ create a function similar to while, if, or for

Think about this code in C/C++:
bool cond = true;
while(cond){
std::cout << "cond is currently true!";
}
Is it possible to create a function that can be called like this?
myFunction(some_parameters_here){
//Code to execute, maybe use it for callbacks
myOtherFunction();
anotherFunction();
}
I know you can use function pointers and lambda functions, but I was wondering if you can. I'm pretty sure there is a way to do so, because how would while() exist?
while(condition) { expression } is not a function but a control structure / a separate language construct; it executes expression again and again as long as condition evaluates to true (i.e. something != 0).
an function definition of the form void myFunction(int someParameter) { expression }, in contrast, is executed only when it is called by another function.
Hope it helps a bit;
Caution: this solution comes without the guarantee that your code reviewer will like it.
We can use a trick similar to the one Alexandrescu uses for his SCOPE_EXIT macro (awesome one-hour conference, this bit is at 18:00).
The gist of it: a clever macro and a dismembered lambda.
namespace myFunction_detail {
struct Header {
// Data from the construct's header
};
template <class F>
void operator * (Header &&header, F &&body) {
// Do something with the header and the body
}
}
#define myPrefix_myFunction(a, b, c) \
myFunction_detail::Header{a, b, c} * [&]
Using it as follows:
myPrefix_myFunction(foo, bar, baz) {
}; // Yes, we need the semicolon because the whole thing is a single statement :/
... reconstitutes a complete lambda after macro expansion, and lands into myFunction_detail::operator* with acess to foo, bar, baz, and the body of the construct.

Unusual C++ function declaration

There are a few legal ways which can we declare a function in C++.
Some of the legal ways are:
void function ();
void function (void);
dataType function (dataType);
and so on...
Recently, I came across a function declaration as such:
void (function) (); //Take note of the braces around the function name
I have never seen somehting like this before, when I tested it in a C++ compiler, it runs without any warning or compilation errors.
My question is: Why is void (function) (); a legal way to decalre a function prototype? Is there any special meaning to declare a function in this way? Or does it just work normally like any other function declaration?
One difference is that enclosing it in parenthesis prevents the function-like macros expansion by the preprocessor. As mentioned in the other answers it makes no difference though to the actual compiler.
For instance:
// somewhere buried deep in a header
#define function(a, b) a + b
// your code
void function() { // this expands the macro and gives compilation error
}
void (function)() { // this does not expand and works as expected
}
This comes in handy for instance when the bright minds behind the Microsoft Visual Studio library decided to provide function-like macros for things like min and max. (There are other ways like #undef to go around this).
Note that object-like macros (e.g. #define function 3 + 4) are still expanded.
The preprocessor is just a dumb text replacement tool (as opposed to the compiler which is just a (smart) text replacement tool). It takes the macro definition and replaces it everywhere. He is not aware of the semantics of what he replaces.
For instance:
// somewhere buried deep in a header
#define function 3 + 2
// your code
void function() {
}
The preprocessor sees the word function and textually replaces it with the string 3 + 2. He is unaware that function is a id-name part of a function declaration and definition. After the preprocess phase there come the actual compile phases. So the compiler actually sees:
// your code
void 3 + 2() {
}
which does not make any sense to him and gives an error.
For function-like macros
// somewhere buried deep in a header
#define function(a, b) a + b
The preprocessor does the same except that it expects two ‘tokens’ enclosed in parenthesis separated by comma (the parameters) and does the replacement. (again no semantics aware):
int d = function(2, 3);
//will be replaced by the preprocessor to:
int d = 2 + 3; // passes compilation phase
void function();
// the preprocessor doesn’t find the arguments for function so it gives an error.
However if it encounters (function) it will not try to expand it (it ignores it). It is just a rule.
it's the same as
void function();
you can declare it as
void ((function)) ();
if you want :)
be careful not to mix this up with the function pointer declaration syntax.
There is nothing special about it, it means exactly the same as the version without parentheses. It is just an artifact of how the syntax is declared. Usually you see the use of parentheses around the function name when a function pointer is declared, e.g.
void (*function_pointer)() = nullptr;
// a function pointer to a function taking and returning void
in contrast to
void *function();
// a function declaration of a function taking void and returning void*
I think it works the same as a normal function because function pointers are declared like: void (*function)() so if you leave out the * then it should be just a function.
It corresponds to the C++ grammar. If to simplify then one of the rules for defining of the declarator looks as
declarator:
(declarator)
So you can write for example
void (function) ();
or
void ( (function) () );
or even the following way
struct A
{
void ( ( function )() const );
};
I think you may find that was:
void (*function) ();
since there is no benefit to using void (function)(); or void (((((function)))))(); for that matter, they're equivalent. If I'm mistaken and it's not a typo, the answer is that you can put as many parentheses around the function name as you like, subject to compiler limitations, as per the code for output6() below.
If I'm not mistaken, that one with the * actually declares a function pointer which can be used to hold a pointer to a function. It does not declare a function at all, just a pointer that can be used to reference a function.
Like an int pointer (for example), the function pointer can point to an arbitrary function, parameters notwhithstanding.
So for example:
#include <iostream>
void (((((output6)))))() { std::cout << 6; }
void output7() { std::cout << 7; }
void output8() { std::cout << 8; }
void (*fn)();
int main() {
fn = &output6; fn();
fn = &output7; fn();
fn = &output8; fn();
std::cout << '\n';
}
would output 678.

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

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?