0

此問題涉及C++ 03。跨命名空間覆蓋運算符

在我的命名空間中,我從不同的命名空間鍵入一個類,然後嘗試爲該類重載一個運算符。我明白,typedef只是一個別名,而不是一個新類型,因此當我的重載中的ADL踢腳沒有被使用。起初,這對我來說並不直觀。我想知道是否有辦法「選擇」我的超負荷,或以某種方式將ADL「引導」到正確的名稱空間?

下面是一個簡化的情況:

#include <iostream> 

namespace boost 
{ 
    template<typename T> 
    struct some_type{}; 

    template<typename T, typename U> 
    T& operator<<(T& os, some_type<U> const& obj) 
    { 
     os << "Boost implementation"; 
     return os; 
    } 
} 

namespace my 
{ 
    typedef boost::some_type<int> typedefed_type; 

    template<typename T> 
    T& operator<<(T& os, typedefed_type const& obj) 
    { 
     os << "My implementation"; 
     return os; 
    } 
} 

namespace other 
{ 
    template<typename T> 
    void f(T const& obj) 
    { 
     // using namespace my; // *** 
     std::cout << obj << std::endl; 
    } 
} 

int main(int argc, char* argv[]) 
{ 
    my::typedefed_type obj; 
    other::f(obj); 
    return 0; 
} 

在這裏,我打電話other::f()::my對象,即使obj確實是一類在boost一個typedef。這輸出:Boost implementation。我能做些什麼來讓My implementation運行?標記爲// ***的行似乎是這樣做的,但我寧願沒有other::f()關心模板參數來自哪些名稱空間。

+0

你不能劫持像這樣的其他人的重載。圍繞some_type使用適當的包裝類型,而不是typedef。 –

+0

@ n.m。,你是在說「不應該」還是「不能」? –

+0

@RSahu我想我說「不能」。等等,讓我檢查一下...... *看一下上面的註釋* ...是的,肯定是「不可以」。 –

回答

1

通過在自己的文件中使用相同的命名空間重載函數,可以劫持名稱空間中的通用實現boost

繼續擁有自己的通用實現在my命名空間,然後添加:

namespace boost 
{ 
    typedef some_type<int> typedefed_type; 

    template<typename T> 
    T& operator<<(T& os, typedefed_type const& obj) 
    { 
     return my::operator<<(os, obj); 
    } 
} 

然後,你的<<操作者的使用可以在other命名空間是簡單的。

namespace other 
{ 
    template<typename T> 
    void f(T const& obj) 
    { 
     std::cout << obj << std::endl; 
    } 
}