2017-03-05 56 views
4

我知道下面的代碼塊是無效的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 S其中一個屬性會,如:

// 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但其他工具鏈不需要的屬性)。

回答

3

不,您不能將屬性放在名稱空間中,或者將它們與名稱空間相關聯。只需定義一個宏。將定義放在頭文件中,以便不同的編譯器可以選擇不同的適合版本的頭文件。

+1

這正是我現在正在應用的解決方案,我只是想知道我是否忽略了標準中允許我將屬性上下文化的任何內容。如果情況是這樣,我認爲屬性說明符並沒有對當前依賴於編譯器的屬性提供真正的改進(或者至少在大多數編譯器具有體面的C++ 17支持,其中未知屬性被忽略之前)。順便說一句,你認爲委員會有可能添加「user-namespaced」屬性說明符嗎? –

+0

@FlávioLisbôa:我不知道,但看看(https://isocpp.org/forums)。也許可以在那裏列出的其中一個組織詢問。 –

+0

@ cheers-and-hth-alf酷,我會試試看。謝謝! –

相關問題