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()
關心模板參數來自哪些名稱空間。
你不能劫持像這樣的其他人的重載。圍繞some_type使用適當的包裝類型,而不是typedef。 –
@ n.m。,你是在說「不應該」還是「不能」? –
@RSahu我想我說「不能」。等等,讓我檢查一下...... *看一下上面的註釋* ...是的,肯定是「不可以」。 –