【问题标题】:How can I properly detect the available C++11 features among GCC versions? [duplicate]如何正确检测 GCC 版本中可用的 C++11 功能? [复制]
【发布时间】:2012-05-04 09:54:48
【问题描述】:

可能重复:
C++11 Feature Checking

我对@9​​87654323@ 规范的案例特别感兴趣,它似乎随着 GCC 4.7 的引入而散布在 C++11 标准库中。在这种情况下,检测编译器版本就足够了;这是生成可移植代码的最佳机制吗?

#include <system_error>

class server_error_category : public std::error_category
{
  public:
    virtual const char* name () const {  ...  }
    //
    // fails beginning with gcc4.7, 
    // looser throw specifier ...
    // overriding 'virtual const char* std::error_category::name() const noexcept (true)

    ...
};

【问题讨论】:

  • Boost.Config 将为不支持 noexcept 规范的编译器定义宏 BOOST_NO_NOEXCEPT。如果您担心 GCC 以外的编译器的可移植性,我建议让 Boost 为您完成艰苦的工作。
  • @ildjam Gar,如果不是最近的话!
  • 你可以使用#if defined(__has_feature) &amp;&amp; __has_feature(cxx_noexcept) 并且保证不会在没有实现它的编译器上使用 noexcept。另一方面,您可能无法在 确实 支持它的编译器上利用 noexcept,因为它们不支持功能检查宏...(AFAIK __has_feature 仅适用于 Clang)跨度>
  • @bames53 : __has_feature 没有标准化,它只是 Clang 特定的扩展。
  • @ildjarn 确实它没有标准化,但它应该是事实上的标准。

标签: c++ gcc c++11 noexcept


【解决方案1】:

如果您只想检查 noexcept 是否在编译时(而不是预处理时)应用于特定方法,您可以简单地使用 noexcept 运算符。

noexcept(std::declval<std::error_category>().name())
// return 'true' if the expression is 'noexcept'

然后你可以使用语法有条件地使方法为 noexcept

virtual const char* name () const
     noexcept(noexcept(std::declval<std::error_category>().name()))
{ ... }

您无法检查库是否支持 noexcept 是预处理时间。版本检查是唯一的方法。

但无论如何你都可以直接输入noexcept。即使基类不是noexcept,子类的覆盖也是有效的。

virtual const char* name () const noexcept { ... }
// valid even in 4.6.

(请注意,Boost.Config 并没有真正的帮助,因为 noexcept 从 4.6 开始在该语言中得到支持,但库的使用出现在 4.7 中。)

【讨论】:

    猜你喜欢
    • 2016-01-22
    • 2015-10-17
    • 1970-01-01
    • 2012-08-19
    • 2014-09-21
    • 1970-01-01
    • 2021-12-18
    • 2014-05-27
    • 2013-09-10
    相关资源
    最近更新 更多