2

I want to write some code to be compatible with different boost versions, and want to use appropriate functions for the given boost versions. Right now I am trying,

#if BOOST_VERSION>105000
#define boost_sleep boost::this_thread::sleep_for
#define millisectime boost::chrono::milliseconds
#define     timed_join try_join_for
#else
#define boost_sleep boost::this_thread::sleep
#define millisectime boost::posix_time::milliseconds
#endif

Which seem to compile fine. I am using it in the code with something like,

// Wait for no reason,
boost_sleep(millisectime(1000));

if( !(workerThread->timed_join(millisectime(1000)) )){
    cout << "Not joined on time" << endl;
    workerThread->detach();
}

Is there a better/standard way to do this? any suggestions to improve this?

2
  • 2
    As an aside: All the code you're writing is standard C++ as of C++11 Commented Jan 12, 2017 at 13:25
  • Yeah, plan is to move to C++11, but for now I am trying to change the least amount of code possible..! lol. (I still need boost for multiindex containers) Commented Jan 12, 2017 at 13:30

2 Answers 2

2

The macro works, but has the problem that you might accidentally replace something other than the function of boost. Maybe one of the third party headers that you include happen to define a variable, or a function or anything with identifier timed_join or millisectime. Perhaps that definition is in an undocumented implementation detail namespace.

Macro replacement for types: A type alias.

typedef boost::
#if BOOST_VERSION>105000
    chrono
#else
    posix_time
#endif
    ::milliseconds millisectime;

Macro replacement for functions: A wrapper function.

void boost_sleep(millisectime m) {
    return boost::this_thread::sleep
#if BOOST_VERSION>105000
    _for
#endif
    (m);
}

Wrapping the member function will change the usage slightly

void timed_join(boost_thread_type& t, millisectime m) {
    t->
#if BOOST_VERSION>105000
    try_join_for
#else
    timed_join
#endif
    (m);
}

Usage:

timed_join(workerThread, millisectime(1000));
Sign up to request clarification or add additional context in comments.

Comments

2

Your definitions are aliases; C++ doesn't need a preprocessor for that.

I.e.

#if BOOST_VERSION>105000
using millisectime = boost::chrono::milliseconds;
void boost_sleep(millisectime t) { boost::this_thread::sleep_for(t); }
#else
...

2 Comments

Wait it gave me an error when I did the first one, saying milliseconds is not a member...! But I'll check, thx!
@xcorat: I just copied your names.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.