C++20中的Feature Test Mocros

      C++20定义了一组预处理器宏,用于测试各种语言和库的feature。

      Feature Test Mocros(特性测试宏)是C++20中引入的一种强大机制,用于应对兼容性问题。Feature Test Mocros作为预处理器指令(preprocessor directives)出现,它使你能够在编译过程中仔细检查特定语言或库功能(particular language or library feature)是否获得编译器的支持。这种方式提供了一种查询编译器功能的统一方法,从而有助于无缝调整代码库。通过战略性地使用Feature Test Mocros,开发人员能够识别所选功能(feature)的可用性。因此,这允许根据特定属性的存在与否来有条件地组装代码段。总体结果是在一系列编译器和C++标准的不同版本中保留代码功能

      C++20引入了一套以_cpp为前缀的预定义宏。利用这些宏作为工具来评估所需功能的存在。将取决于特定功能的代码段封装在#ifdef和#endif预处理器指令中。定义宏时,相应的代码块将在编译过程中集成;相反,如果宏仍未定义,则编译时会省略该块

      (1).language features:宏是在每个翻译单元(translation unit)中预定义的。当工作草案(working draft)中包含了相应的feature时,每个宏都扩展为一个与年份和月份相对应的整数字面值。当一个feature发生重大变化时,宏将相应地更新。

      (2).library features:如果包含头文件<version>或对应的头文件例如<any>,则会定义对应宏。当工作草案(working draft)中包含了相应的feature时,每个宏都扩展为一个与年份和月份相对应的整数字面值。当一个feature发生重大变化时,宏将相应地更新。

      头文件<version>

      (1).此头文件是language support library的一部分。此头文件提供有关标准库的实现相关信息(例如特定于实现的库版本宏)。

      (2).定义了很多library feature-test macros,在实现该feature时扩展为一个数字。这个数字表示该feature被添加到C++标准中的年份和月份。

      支持的宏列表:https://en.cppreference.com/w/cpp/feature_test 

      以下为测试代码:

int test_feature_test_macros()
{
	// language features
#ifdef __cpp_constexpr
	std::cout << "support constexpr" << std::endl;
#else
	std::cout << "Warning: unsupport constexpr" << std::endl;
#endif

#ifdef __cpp_structured_bindings
	std::cout << "support structured bindings" << std::endl;
#else
	std::cout << "Warning: unsupport structured bingdings" << std::endl;
#endif

#ifdef __cpp_consteval
	std::cout << "support consteval" << std::endl;
#else
	std::cout << "Warning: unsupport consteval" << std::endl;
#endif

#ifdef __cpp_aggregate_paren_init
	std::cout << "support aggregate paren init" << std::endl;
#else
	std::cout << "Warning: unsupport aggregate paren init" << std::endl;
#endif

	// library features
#ifdef __cpp_lib_ranges
	std::cout << "ranges library available" << std::endl;
#else
	std::cout << "Warning: ranges library unavailable" << std::endl;
#endif

#ifdef __cpp_lib_filesystem
	std::cout << "filesystem library available" << std::endl;
#else
	std::cout << "Warning: filesystme library unavailable" << std::endl;
#endif

#ifdef __cpp_lib_any
	std::cout << "any library available" << std::endl;
#else
	std::cout << "Warning: any library unavailable" << std::endl;
#endif

#ifdef __cpp_lib_fbc
	std::cout << "fbc library available" << std::endl;
#else
	std::cout << "Warning: fbc library unavailable" << std::endl;
#endif

	return 0;
}

      执行结果如下图所示:选择不同的C++语言标准(C++14/C++17/C++20),输出结果不同

      GitHubhttps://github.com/fengbingchun/Messy_Test

  • 8
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值