2012-08-28 49 views
0

如果我的對象需要打印std::wstring以及整數等,我該如何編寫輸出operator<<如何將int打印到std :: wcerr?

#include <iostream> 

struct Foo { 
    int i; 
    std::wstring wstr; 
}; 

std::ostream& operator<<(std::ostream& out, Foo const& foo) { 
    out << foo.i << foo.wstr; // error                        
    return out; 
} 

int main() { 
    Foo foo; 
    std::wcerr << foo << std::endl; 
} 

換句話說:我怎樣才能打印int S和其他基本數據類型,如果我通過了wcerr?我需要boost::lexical_cast<std::wstring>還是類似的?

回答

1
#include <iostream> 

struct Foo { 
    int i; 
    std::wstring wstr; 
}; 

std::wostream& operator<<(std::wostream& out, Foo const& foo) { 
    out << foo.i << foo.wstr;                        
    return out; 
} 

int main() { 
    Foo foo; 
    std::wcerr << foo << std::endl; 
}