【问题标题】:Preprocessor macros for different function names不同函数名的预处理器宏
【发布时间】:2017-01-12 13:20:34
【问题描述】:

我想编写一些代码来兼容不同的 boost 版本,并希望为给定的 boost 版本使用适当的函数。现在我正在尝试,

#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

这似乎编译得很好。我在代码中使用它,例如,

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

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

有没有更好/标准的方法来做到这一点?有什么改进的建议吗?

【问题讨论】:

  • 顺便说一句:从 C++11 开始,您编写的所有代码都是标准 C++
  • 是的,计划是迁移到 C++11,但现在我正在尝试尽可能少地更改代码..!哈哈。 (我仍然需要多索引容器的提升)

标签: c++ boost c-preprocessor


【解决方案1】:

这个宏可以工作,但有一个问题是你可能会不小心替换了boost功能以外的东西。也许您包含的第三方标头之一恰好定义了一个变量、一个函数或任何标识符为timed_joinmillisectime 的东西。也许该定义位于未记录的实现细节命名空间中。

类型的宏替换:类型别名。

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

函数的宏替换:包装函数。

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

包装成员函数会稍微改变用法

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

用法:

timed_join(workerThread, millisectime(1000));

【讨论】:

    【解决方案2】:

    您的定义是别名; C++ 不需要预处理器。

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

    【讨论】:

    • 等我做第一个时它给了我一个错误,说毫秒不是成员......!但我会检查的,谢谢!
    • @xcorat:我刚刚复制了你的名字。
    猜你喜欢
    • 2010-11-11
    • 2020-05-29
    • 1970-01-01
    • 1970-01-01
    • 2014-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多