Is there a way to create a namespace with generic attributes?

I know that the following snippet of source code is invalid with C ++ code, but just to illustrate my question:

#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;
}

Is there any way to achieve this? The goal is to discard #defineand use attribute specifiers exclusively - excluding compiler protection and verification, because it will certainly require some degree of preprocessing-fu proficiency :) (but then predef is your friend ).

For instance:

// 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();

My current solution is to use #definewhere the attribute will be, for example:

// 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, ).

+4
1

, . . , .

+3

Source: https://habr.com/ru/post/1671540/


All Articles