我知道以下源代码不是有效的 C++ 代码,但只是为了说明我的问题:
#include <iostream>
namespace mylib {
using deprecated = [[deprecated]];
}
[[mylib::deprecated]] void deprecated_function() {
std::cout << "Calling deprecated function!" << std::endl;
}
int main(void) {
deprecated_function();
return 0;
}
有什么办法可以实现这样的事情吗?目的是删除 #define
并专门使用属性说明符——不包括编译器保护和验证,因为这肯定需要一定程度的预处理能力 :)(但是,predef is your friend ).
例如:
// mylib-config.hpp
namespace mylib {
#if __cplusplus > 201402L // C++17 has support for [[deprecated]]
using deprecated = [[deprecated]]
#elif defined(__clang)
using deprecated = [[clang::deprecated]]
#elif defined(__GNUC__)
using deprecated = [[gnu::deprecated]]
#else // What to do? Is there a placeholder?
// Starting C++17, this invalid attribute should be ignored.
// Before that, the result is implementation-defined.
// (Is there any chance for undefined behaviour in this case?)
using deprecated = [[completely_invalid_identifier__]];
#endif
}
// mylib.hpp
[[mylib::deprecated]] void deprecated_function();
我目前的解决方案是在属性所在的位置使用 #define
,例如:
// mylib-config.hpp
#if __cplusplus > 201402L
#define mylib_DEPRECATED [[deprecated]]
#elif defined(__clang)
#define mylib_DEPRECATED [[clang::deprecated]]
#elif defined(__GNUC__)
#define mylib_DEPRECATED [[gnu::deprecated]]
#else
#define mylib_DEPRECATED
#endif
// mylib.hpp
mylib_DEPRECATED void deprecated_function();
如果在您自己的命名空间中规范化您的应用程序使用的所有属性确实是可能的,您将如何解释某些编译器上缺少特定属性的情况? (例如,仅适用于 GCC 但其他工具链不需要的属性)。
最佳答案
不,您不能将属性放入命名空间中,或将它们与命名空间相关联。定义一个宏就行了。将定义放在 header 中,这样不同的编译器将选择该 header 的不同、合适的版本。
关于c++ - 有没有办法创建具有通用属性的 namespace ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42614263/