簡體   English   中英

跨命名空間的基於 SFINAE 的運算符重載

[英]SFINAE-based Operator Overloading across Namespaces

我正在嘗試使用一種允許為強類型枚舉類自動啟用位掩碼運算符的方法。 請參閱下面的示例的標題和 cpp。

https://www.justsoftwaresolutions.co.uk/files/bitmask_operators.hpp https://www.justsoftwaresolutions.co.uk/files/testbitmask.cpp

testbitmask.cpp 中的方法在所有內容都在同一個命名空間中時有效,但是我想將不同命名空間中的 SFINAE 代碼與其他類的使用分開(見下文或https://wandbox.org/permlink/05xXaViZT3MVyiBl ) .

#include <type_traits>

namespace ONE {
    template<typename E>
    struct enable_bitmask_operators{
        static const bool enable=false;
    };

    template<typename E>
    inline typename std::enable_if<enable_bitmask_operators<E>::enable,E>::type
    operator|(E lhs,E rhs){
        typedef typename std::underlying_type<E>::type underlying;
        return static_cast<E>(
            static_cast<underlying>(lhs) | static_cast<underlying>(rhs));
    }
}

namespace TWO {
    enum class A{ x=1, y=2};
}

namespace ONE {
    template<>
    struct enable_bitmask_operators<TWO::A>{
        static const bool enable=true;
    };
}

int main(){
    TWO::A a1 = TWO::A::x | TWO::A::y;
}

這會導致無法在 main 中找到重載的運算符。 顯式調用該函數有效( TWO::A a1 = ONE::operator|(TWO::A::x , TWO::A::y); ),但當然不是所需的功能。

如果我們將特化移到namespace ONE ,編譯器會拋出一個error: declaration of 'struct ONE::enable_bitmask_operators<TWO::A>' in namespace 'TWO' which does not enclose 'ONE' 我想知道在 C++ 中是否可以使用所需的方法?

ADL 找不到您的函數,您可以添加一些using以允許使用它:

using ONE::operator|;
TWO::A a1 = TWO::A::x | TWO::A::y;

演示

using namespace ONE; 也可能是另一種選擇。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM