c++ #define a macro with brackets? - c++

Instead of doing the following everytime
start();
// some code here
stop();
I would like to define some sort of macro which makes it possible to write like:
startstop()
{
//code here
}
Is it possible in C++?

You can do something very close using a small C++ helper class.
class StartStopper {
public:
StartStopper() { start(); }
~StartStopper() { stop(); }
};
Then in your code:
{
StartStopper ss;
// code here
}
When execution enters the block and constructs the ss variable, the start() function will be called. When execution leaves the block, the StartStopper destructor will be automatically called and will then call stop().

The idiomatic way of doing this in C++ is called Resource Acquisition Is Initialization, or shortly RAII. In addition to providing what you want, it also has the added benefit of being exception safe: the stop function will be called even if your code throws an exception.
Define a guard struct:
struct startstop_guard
{
startstop_guard()
{
start();
}
~startstop_guard()
{
stop();
}
};
and then rewrite your code this way:
{
startstop_guard g;
// your code
}
The guard's destructor (and thus the stop function) will be called automatically at the end of the enclosing block.

Other answers have addressed the RAII side of the question well, so I'm going to address the syntax side of it.
#define startstop for(Starter s; s.loop; s.loop = false)
struct Starter {
bool loop;
Starter() { start(); loop = true; }
~Starter() { stop(); }
};
Used like:
startstop {
// some code
}
Should be self-explanatory enough.

#define startstop(x, y, ...) for( /* use macro args */ )

Generic solution with RAII and boost::function ( std::function ).
class starter
{
typedef boost::function< void () > action;
action end_;
public:
starter(action start, action end):
end_(end)
{
log("starter start");
start();
}
~starter()
{
log("starter end");
end_() ;
}
};
int main()
{
{
starter s(start, stop);
middle();
}
return 0;
}
or to test and check the idea
void print(const std::string& message)
{
std::cout << message << std::endl;
}
int main()
{
starter s(boost::bind(print, "globalstart"),
boost::bind(print, "globalend"));
{
starter s(boost::bind(print, "start"),
boost::bind(print, "end"));
std::cout << "middle" << std::endl;
}
return 0;
}

What are you trying to do? I'd recommend checking out RAII as a much more C++ oriented way of doing things than macro hacking, with all its unforeseen consequences.

Don't use macros. You can use inline functions instead as it provides type checking and other features. You can take a look here: inline functions

credit to dirkgently for the idea.. I thought I'd fill the rest in
#define startstop() for(start();isStarted();stop())

In c#, you could use the IDisposable pattern, and implement your Stop() functionality in the Dispose() method, but that would would work if you were using a .net variant of c++.

Related

Static statements inside a function [duplicate]

I have an application which has several functions in it. Each function can be called many times based on user input. However I need to execute a small segment of the code within a function only once, initially when the application is launched. When this same function is called again at a later point of time, this particular piece of code must not be executed. The code is in VC++. Please tell me the most efficient way of handling this.
Compact version using lambda function:
void foo()
{
static bool once = [](){
cout << "once" << endl;
return true;
} ();
cout << "foo" << endl;
}
Code within lambda function is executed only once, when the static variable is initialized to the return value of lambda function. It should be thread-safe as long as your compiler support thread-safe static initialization.
Using C++11 -- use the std::call_once
#include <mutex>
std::once_flag onceFlag;
{
....
std::call_once ( onceFlag, [ ]{ /* my code body here runs only once */ } );
....
}
Use global static objects with constructors (which are called before main)? Or just inside a routine
static bool initialized;
if (!initialized) {
initialized = true;
// do the initialization part
}
There are very few cases when this is not fast enough!
addenda
In multithreaded context this might not be enough:
You may also be interested in pthread_once or constructor function __attribute__ of GCC.
With C++11, you may want std::call_once.
You may want to use <atomic> and perhaps declare static volatile std::atomic_bool initialized; (but you need to be careful) if your function can be called from several threads.
But these might not be available on your system; they are available on Linux!
You can use local static variable:
void foo()
{
static bool wasExecuted = false;
if (wasExecuted)
return;
wasExecuted = true;
...
}
Additionally to #Basile's answer, you can use a lambda to encapsulate the static variable as follows:
if ([] {
static bool is_first_time = true;
auto was_first_time = is_first_time;
is_first_time = false;
return was_first_time; } ())
{
// do the initialization part
}
This makes it easy to convert into a general-purpose macro:
#define FIRST_TIME_HERE ([] { \
static bool is_first_time = true; \
auto was_first_time = is_first_time; \
is_first_time = false; \
return was_first_time; } ())
Which can be placed anywhere you want call-by-need:
if (FIRST_TIME_HERE) {
// do the initialization part
}
And for good measure, atomics shorten the expression and make it thread-safe:
#include <atomic>
#define FIRST_TIME_HERE ([] { \
static std::atomic<bool> first_time(true); \
return first_time.exchange(false); } ())
could you do this
have a function that return a bool or some datatype called init
I made it happen this way, you need static bool to make it happens
bool init()
{
cout << "Once " <<endl;
return true||false;// value isn't matter
}
void functionCall()
{
static bool somebool = init(); // this line get executed once
cout << "process " <<endl;
}
int main(int argc, char *argv[])
{
functionCall();
functionCall();
functionCall();
return EXIT_SUCCESS;
}
for C
#include <stdio.h>
void init()
{
printf("init\n");
}
void process()
{
static int someint = 0;
if(someint == 0)
{
someint = 1;
init();
}
printf("process\n");
}
int main()
{
process();
process();
process();
return 0;
}
std::call_once() et al. may be overkill if you don't need a totally thread-safe solution.
If not, we can make this look especially elegant when using C++17's initialisation-within-if and std::exchange():
#include <utility>
void
do_something_expensive_once()
{
if ( static auto called = false; !std::exchange(called, true) ) {
do_something_expensive();
}
}
If this is a pattern you use a lot, then we can encapsulate it via a tag type:
#include <iostream>
#include <utility>
template <typename T>
auto
call_once()
{
static auto called = false;
return !std::exchange(called, true);
}
void
do_something_expensive()
{
std::cout << "something expensive\n";
}
void
do_something_expensive_once()
{
if ( call_once<struct TagForSomethingExpensive>() ) {
do_something_expensive();
}
}
auto
main() -> int
{
for (auto i = 0; i < 5; ++i) {
do_something_expensive_once();
}
return 0;
}
This will only print something expensive a single time. Result! It also uses the ability to declare a tag struct in a template argument list, for maximal brevity.
Alternatively, you could template on a function's address, a unique integer, etc.
You can then also pass a callable to call_once(), and so on, and so forth. As usual for C++: the possibilities are endless!
With due respect to std::call_once() and the usual caveats about thread safety, here's another lightweight option which avoids unused variable warnings and keeps our flag in block scope:
for (static bool once=true; once; once=false) {
yourCodeHere();
}
Another simple solution is:
#define execute_once if(static bool b = false; b) ; else if((b = true))
Used thus:
execute_once std::cout << "Hi mum!\n";
or:
execute_once
{
std::cout << "These statements are ";
std::cout << "only executed once\n";
}
It's not thread safe, obviously. (EDIT: although just using a std::atomic_bool in place of the bool would get you there I think.)
do {
//execute code once
} while (false)

Callable function C++

I've read various answer on SO and still didn't understood how I should make an object method to be callable in this case:
Considering:
Class A
{
void generator(void)
{
int i = 1;
while(1)
{
if(i == 1)
{
one(/***/);//Should be a flag
i = 2;
}
else
{
two(/**/);//Should be a flag
i = 1;
}
}
}
template <typename CallbackFunction>
void one(CallbackFunction&& func)
{
}
template <typename CallbackFunction>
void two(CallbackFunction&& func)
{
}
A()
{
std::thread t(&A::generator, this);
t.detach();
}
};
and a simple main file:
void pOne(/**/)
{
std::cout<<"1"<<std::endl;
}
void pTwo(/**/)
{
std::cout<<"2"<<std::endl;
}
A myA;
A.One(pOne);
A.Two(pTwo);
int main(int argc, char** argv)
{
while(1){}
}
Here are where I'm at:
generator() should update a flag, and both one() & two() should poll on that flag & loop forever.
One() (two() also) should have a function pointer as parameters and if necessary other parameters, pOne() should have the same parameters except the function pointer.
So my questions are:
1) Is my understanding correct?
2) Is there a clean way to make generator() to start one() or two() ? (flags, semaphore, mutex, or anything that is a standard way to do it)
3) Assuming that the code was working, is it behaving as I expect ? i.e. printing 1 and 2?
if it matters, I'm on ubuntu
Disclaimer 1: Like everyone else, I'm interpreting the question as:
-> You need an event handler
-> You want callback methods on those events
And the only reason I think that is because I helped you on a i2c handler sequence before.
Also, there are better logic than this, its provided following your stubs "rules".
You mentioned that you are on Ubuntu, so you will be lacking windows event system.
Disclaimer 2:
1- To avoid going to deep I'm going to use a simple way to handle events.
2- Code is untested & provided for logic only
class Handler
{
private:
std::mutex event_one;
event_one.lock();
void stubEventGenerator(void)
{
for(;;)
{
if(!event_one.try_lock())
{
event_one.unlock();
}
sleep(15); //you had a sleep so I added one
}
}
template <typename CallbackFunction>
void One__(CallbackFunction && func)
{
while(1)
{
event_one.lock();
func();
}
}
public:
Handler()
{
std::thread H(&Handler::stubEventGenerator, this);
}
~Handler()
{
//clean threads, etc
//this should really have a quit handler
}
template <typename CallbackFunction>
void One(CallbackFunction && func) //I think you have it right, still I'm not 100% sure
{
std::thread One_thread(&Handler::One__, this, func); //same here
}
};
Some points:
One() as to be a wrapper for the thread calling One__() if you want it to be non-blocking.
mutex can be a simple way to handle events as long as the same event doesn't occur during its previous occurence (you are free to use a better/more suitable tool for your use case, or use boost:: only if necessary)
Prototype of One() & One__() are probably wrong, that's some research for you.
Finally: How it works:
std::mutex.lock() is blocking as long as it can't lock the mutex, thus One__ will wait as long as your event generator won't unlock it.
Once unlock One__ will execute your std::function & wait for the event (mutex) to be raised (unlock) again.
far from a perfect answer, but lack of time, and not being able to put that in a comment made me post it, will edit later
With whatever limited information you provided this code can be made compilable in following manner:
#include <iostream>
#include <thread>
typedef void(*fptr)();
void pOne(/**/)
{
std::cout<<"1"<<std::endl;
}
void pTwo(/**/)
{
std::cout<<"2"<<std::endl;
}
class A
{
public:
void generator(void)
{
int i = 1;
while(1)
{
if(i == 1)
{
fptr func = pOne;
one(func);//Should be a flag
i = 2;
}
else
{
fptr func = pTwo;
two(func);//Should be a flag
i = 1;
}
}
}
template <typename CallbackFunction>
void one(CallbackFunction&& func)
{
func();
}
template <typename CallbackFunction>
void two(CallbackFunction&& func)
{
func();
}
A()
{
std::thread t(&A::generator, this);
t.detach();
}
};
int main()
{
A myA;
while(1)
{
}
return 0;
}
If you want that one and two should accept any type/number of arguments then pass second argument as variadic template.Also I could not understand why you want one and two to be called from main as your generator function is for this purpose only and this generator function is called from thread which is detached in class constructor

How to execute a piece of code only once?

I have an application which has several functions in it. Each function can be called many times based on user input. However I need to execute a small segment of the code within a function only once, initially when the application is launched. When this same function is called again at a later point of time, this particular piece of code must not be executed. The code is in VC++. Please tell me the most efficient way of handling this.
Compact version using lambda function:
void foo()
{
static bool once = [](){
cout << "once" << endl;
return true;
} ();
cout << "foo" << endl;
}
Code within lambda function is executed only once, when the static variable is initialized to the return value of lambda function. It should be thread-safe as long as your compiler support thread-safe static initialization.
Using C++11 -- use the std::call_once
#include <mutex>
std::once_flag onceFlag;
{
....
std::call_once ( onceFlag, [ ]{ /* my code body here runs only once */ } );
....
}
Use global static objects with constructors (which are called before main)? Or just inside a routine
static bool initialized;
if (!initialized) {
initialized = true;
// do the initialization part
}
There are very few cases when this is not fast enough!
addenda
In multithreaded context this might not be enough:
You may also be interested in pthread_once or constructor function __attribute__ of GCC.
With C++11, you may want std::call_once.
You may want to use <atomic> and perhaps declare static volatile std::atomic_bool initialized; (but you need to be careful) if your function can be called from several threads.
But these might not be available on your system; they are available on Linux!
You can use local static variable:
void foo()
{
static bool wasExecuted = false;
if (wasExecuted)
return;
wasExecuted = true;
...
}
Additionally to #Basile's answer, you can use a lambda to encapsulate the static variable as follows:
if ([] {
static bool is_first_time = true;
auto was_first_time = is_first_time;
is_first_time = false;
return was_first_time; } ())
{
// do the initialization part
}
This makes it easy to convert into a general-purpose macro:
#define FIRST_TIME_HERE ([] { \
static bool is_first_time = true; \
auto was_first_time = is_first_time; \
is_first_time = false; \
return was_first_time; } ())
Which can be placed anywhere you want call-by-need:
if (FIRST_TIME_HERE) {
// do the initialization part
}
And for good measure, atomics shorten the expression and make it thread-safe:
#include <atomic>
#define FIRST_TIME_HERE ([] { \
static std::atomic<bool> first_time(true); \
return first_time.exchange(false); } ())
could you do this
have a function that return a bool or some datatype called init
I made it happen this way, you need static bool to make it happens
bool init()
{
cout << "Once " <<endl;
return true||false;// value isn't matter
}
void functionCall()
{
static bool somebool = init(); // this line get executed once
cout << "process " <<endl;
}
int main(int argc, char *argv[])
{
functionCall();
functionCall();
functionCall();
return EXIT_SUCCESS;
}
for C
#include <stdio.h>
void init()
{
printf("init\n");
}
void process()
{
static int someint = 0;
if(someint == 0)
{
someint = 1;
init();
}
printf("process\n");
}
int main()
{
process();
process();
process();
return 0;
}
std::call_once() et al. may be overkill if you don't need a totally thread-safe solution.
If not, we can make this look especially elegant when using C++17's initialisation-within-if and std::exchange():
#include <utility>
void
do_something_expensive_once()
{
if ( static auto called = false; !std::exchange(called, true) ) {
do_something_expensive();
}
}
If this is a pattern you use a lot, then we can encapsulate it via a tag type:
#include <iostream>
#include <utility>
template <typename T>
auto
call_once()
{
static auto called = false;
return !std::exchange(called, true);
}
void
do_something_expensive()
{
std::cout << "something expensive\n";
}
void
do_something_expensive_once()
{
if ( call_once<struct TagForSomethingExpensive>() ) {
do_something_expensive();
}
}
auto
main() -> int
{
for (auto i = 0; i < 5; ++i) {
do_something_expensive_once();
}
return 0;
}
This will only print something expensive a single time. Result! It also uses the ability to declare a tag struct in a template argument list, for maximal brevity.
Alternatively, you could template on a function's address, a unique integer, etc.
You can then also pass a callable to call_once(), and so on, and so forth. As usual for C++: the possibilities are endless!
With due respect to std::call_once() and the usual caveats about thread safety, here's another lightweight option which avoids unused variable warnings and keeps our flag in block scope:
for (static bool once=true; once; once=false) {
yourCodeHere();
}
Another simple solution is:
#define execute_once if(static bool b = false; b) ; else if((b = true))
Used thus:
execute_once std::cout << "Hi mum!\n";
or:
execute_once
{
std::cout << "These statements are ";
std::cout << "only executed once\n";
}
It's not thread safe, obviously. (EDIT: although just using a std::atomic_bool in place of the bool would get you there I think.)
do {
//execute code once
} while (false)

How to initial static member in C++ using function

I am using C++.
in .h:
static CRITICAL_SECTION g_CS;
in .cpp:
CRITICAL_SECTION CQCommon::g_CS;
but I want to use
QGUID temp;
EnterCriticalSection(&g_CS);
temp = g_GUID++;
LeaveCriticalSection(&g_CS);
return temp;
in one static function.
How can I invoke InitializeCriticalSection(PCRITICAL_SECTION pcs);?
Can I using the following one:
QGUID func(XXX)
{
static {
InitializeCriticalSection(&g_CS);
}
QGUID temp;
EnterCriticalSection(&g_CS);
temp = g_GUID++;
LeaveCriticalSection(&g_CS);
return temp;
}
And how can I invoke DeleteCriticalSection(&g_CS) after app leave?
Using MFC, it seems CCriticalSection is a solution.
If you want a different approach you can create an object to manage it:
class CriticalSectionManager
{
public:
CriticalSectionManager()
{
InitializeCriticalSection(&g_CS);
}
~CriticalSectionManager()
{
DeleteCriticalSection(&g_CS);
}
};
void Func(void)
{
static CriticalSectionManager man;
//Do stuff
}
This will now be managed automatically by C++. The critical section will be initialized when the function is first entered, and deleted when the program exits.
Furthermore you can extend this by having the actual PCRITICAL_SECTION variable inside the class, etc.. etc..
In the entry point to your code - the main function, call the init:
int main(...)
{
InitializeCriticalSection(&g_CS);
// do some stuff
DeleteCriticalSection(&g_CS);
// exit
return 0;
}
Well, today the best practice is to use "scoped lock" pattern instead of EnterXXX and LeaveXX -like functions. Take a look at what boos has to offer.
Regardless, an RAII approach can help you here:
class MyCriticalSection
{
private:
CRITICAL_SECTION m_CS;
public:
MyCriticalSection()
{
::InitializeCriticalSection(&m_CS);
}
~MyCriticalSection()
{
::DeleteCriticalSection(&m_CS);
}
void Lock()
{
::EnterCriticalSection(&m_CS);
}
void UnLock()
{
::LeaveCriticalSetion(&m_CS);
}
}

Iterating over vector and calling functions

I have a class that has a vector of another class objects as a member. In many functions of this class I have to do same operation on all the objects in the vector:
class Small
{
public:
void foo();
void bar(int x);
// and many more functions
};
class Big
{
public:
void foo()
{
for (size_t i = 0; i < VectorOfSmalls.size(); i++)
VectorOfSmalls[i]->foo();
}
void bar(int x)
{
for (size_t i = 0; i < VectorOfSmalls.size(); i++)
VectorOfSmalls[i]->bar(x);
}
// and many more functions
private:
vector<Small*> VectorOfSmalls;
};
I want to simplify the code, and find a way not to duplicate going other the vector in every function.
I've considered creating a function that receives a pointer to function, and calls the pointed function on every member of a vector. But I am not sure that using pointers to functions in C++ is a good idea.
I have also been thinking about functors and functionoids, but it will force me to create a class per each function and it sounds like an overkill.
Another possible solution is creating a function that receives a string, and calls the command according to the string:
void Big::call_command(const string & command)
{
for (size_t i = 0; i < VectorOfSmalls.size(); i++)
{
if (command == "foo")
VectorOfSmalls[i]->foo();
else if (command == "bar")
VectorOfSmalls[i]->bar();
}
}
void Big::foo()
{
call_command("foo");
}
But it might work slow (unneeded creation of a string instead of just a function call), and also creates a problem if functions have different signature.
So what would you recommend? Should I leave everything the same as it is now?
EDIT: I can use only STL and not boost (old compilers).
Well you can rewrite the for loops to use iterators and more of the STL like this:
void foo() {
std::for_each(VectorOfSmalls.begin(), VectorOfSmalls.end(), std::mem_fun(&Small::foo));
}
void bar() {
std::for_each(VectorOfSmalls.begin(), VectorOfSmalls.end(), std::mem_fun(&Small::bar));
}
beyond that, you could use some macros to avoid retyping that a lot, but I'm not a huge fan of that. Personally, I like the multiple functions over the single one which takes a command string. As it gives you more versatility over how the decision is made.
If you do go with a single function taking a param to decide which to do, I would use an enum and a switch like this, it would be more efficient than strings and a cascading if. Also, in your example you have the if to decide which to do inside the loop. It is more efficient to check outside the loop and have redundant copies of the loop since "which command" only needs to be decided once per call. (NOTE: you can make the command a template parameter if it is known at compile time, which it sounds like it is).
class Big {
public:
enum Command {
DO_FOO,
DO_BAR
};
void doit(Command cmd) {
switch(cmd) {
case DO_FOO:
std::for_each(VectorOfSmalls.begin(), VectorOfSmalls.end(), std::mem_fun(&Small::foo));
break;
case DO_BAR:
std::for_each(VectorOfSmalls.begin(), VectorOfSmalls.end(), std::mem_fun(&Small::bar));
break;
}
};
Also, as you mentioned, it is fairly trivial to replace the &Small::whatever, what a member function pointer and just pass that as a parameter. You can even make it a template too.
class Big {
public:
template<void (Small::*fn)()>
void doit() {
std::for_each(VectorOfSmalls.begin(), VectorOfSmalls.end(), std::mem_fun(fn));
}
};
Then you can do:
Big b;
b.doit<&Small::foo>();
b.doit<&Small::bar>();
The nice thing about both this and the regular parameter methods is that Big doesn't need to be altered if you change small to have more routines! I think this is the preferred method.
If you want to be able to handle a single parameter, you'll need to add a bind2nd too, here's a complete example:
#include <algorithm>
#include <functional>
#include <iostream>
#include <vector>
class Small {
public:
void foo() { std::cout << "foo" << std::endl; }
void bar(int x) { std::cout << "bar" << std::endl; }
};
class Big {
public:
template<void (Small::*fn)()>
void doit() {
std::for_each(VectorOfSmalls.begin(), VectorOfSmalls.end(), std::mem_fun(fn));
}
template<class T, void (Small::*fn)(T)>
void doit(T x) {
std::for_each(VectorOfSmalls.begin(), VectorOfSmalls.end(), std::bind2nd(std::mem_fun(fn), x));
}
public:
std::vector<Small *> VectorOfSmalls;
};
int main() {
Big b;
b.VectorOfSmalls.push_back(new Small);
b.VectorOfSmalls.push_back(new Small);
b.doit<&Small::foo>();
b.doit<int, &Small::bar>(5);
}
If you're using the std library, you should take a look at for_each.
You mention that using function pointers in C++ might not be a good idea, but -- allowing your worry is speed -- you have to see if this is even a performance bottleneck area you're in, before worrying.
Try boost::function and boost::bind:
void Big::call_command(const boost::function<void (Small*)>& f)
{
for (size_t i = 0; i < VectorOfSmalls.size(); i++)
{
f(VectorOfSmalls[i]);
}
}
int main()
{
Big b;
b.call_command(boost::bind(&Small::foo, _1));
b.call_command(boost::bind(&Small::bar, _1, 5));
}