2012-03-15 81 views
1

我創建了自己<<過載bool,因爲我想它打印truefalse代替10。這通常起作用,除非我離開我定義這個操作符的命名空間。在這種情況下,我得到一個模糊的操作員錯誤。解析不明確的跨運營商的命名空間

error C2593: 'operator <<' is ambiguous 
C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include\ostream(206): could be 'std::basic_ostream<_Elem,_Traits> &std::basic_ostream<_Elem,_Traits>::operator <<(std::_Bool)' 
with 
[ 
    _Elem=char, 
    _Traits=std::char_traits<char> 
] 
c:\Dummy.h(43): or  'std::ostream &Dummy::operator <<(std::ostream &,bool)' 
while trying to match the argument list '(std::basic_ostream<_Elem,_Traits>, bool)' 
with 
[ 
    _Elem=char, 
    _Traits=std::char_traits<char> 
] 

如何指定從哪個命名空間中取出運算符?天真地我試過Dummy::<<Dummy::operator<<,但都沒有成功。

+5

你知道[性病:: boolalpha(HTTP的:// en.cppreference.com/w/cpp/io/manip/boolalpha)? – hmjd 2012-03-15 15:30:10

+0

不,我不是,很高興知道! – Cookie 2012-03-15 15:30:54

回答

5

你應該看看std::boolalpha,但回答你原來的問題:

#include <iostream> 

namespace Dummy { 
    std::ostream& 
    operator<< (std::ostream& stream, bool f) { 
    return stream << (f ? "7RU3" : "F4LS3"); 
    } 
} 

int 
main (int argc, char *argv[]) 
{ 
    std::cerr  << true << "\n"; 
    Dummy::operator<< (std::cerr, true); 
} 

輸出

1 
7RU3