如何优雅打印C++特性测试宏?规避未定义宏编译报错
解决C++特性测试宏未定义时的编译问题
你可以通过预处理器技巧把检测逻辑封装进宏里,避免重复编写冗长的#ifdef代码,下面提供两种实用方案:
方案一:结合defined运算符与标准库函数
这种方案代码更简洁,依赖C++11及以上的std::to_string(标准特性测试宏均为整数类型,适配性没问题):
#include <iostream> #include <string> // 需包含string头文件用于std::to_string #define print(feature) \ std::cout << #feature " : " << \ (defined(feature) ? std::to_string(feature) : std::string("undefined")) << '\n' int main() { print(__cpp_aggregate_bases); print(__cpp_aggregate_nsdmi); print(__cpp_aggregate_paren_init); print(__cpp_auto_cast); print(__cpp_char); }
方案二:纯预处理器条件编译
这种方案兼容性更好,不依赖C++标准库的特定函数,用do-while(0)确保宏在任何语法语境下都能正确执行:
#include <iostream> #define print(feature) \ do { \ std::cout << #feature " : "; \ #ifdef feature \ std::cout << feature; \ #else \ std::cout << "undefined"; \ #endif \ std::cout << '\n'; \ } while(0) int main() { print(__cpp_aggregate_bases); print(__cpp_auto_cast); print(__cpp_char); }
两种方案都能自动处理宏定义与否的情况,编译时不会因未定义的特性宏报错,输出清晰的结果。
内容的提问来源于stack exchange,提问作者Krzysiek Karbowiak
相关产品推荐
相关产品推荐

