c++ - 有没有办法创建具有通用属性的 namespace ?

标签 c++ c++14

我知道以下源代码不是有效的 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/

相关文章:

c++ - C++中的运行时类型转换,如何?

c++ - 使用 gdb 调试 linux 守护进程的初始启动

c++ - 如果方法是在类内部定义的,则防止编译器删除方法

c++ - 类内的 Char 数组初始化

c++ - JsonCpp 不能防止 uint64 溢出并且有奇怪的行为

c++ - 您可以用来学习编程着色器的最佳工具是什么?

c++ - 为什么在类外定义类模板的成员函数时需要模板参数?

c++ - 前向声明 : incomplete type 'enums::Category' used in nested name specifier 有问题

c++ - 有没有什么方法可以在没有 std::move 的情况下调用 C++ 中的移动赋值运算符?

c++ - 模板参数列表中的额外 typename 关键字 : is it valid or not?