Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to reference cout without using namespace std or prefixing with std::?

Tags:

c++

cout

I'm pretty new to C++, and I'm using std::cout for debugging purposes.

Though, I'd really like to be able to just use cout rather than the whole std::cout thing. I know i could import the std namespace, but I've been explained it was a bad thing due to name clashing that can occur because of this.

Is there anyway to do this?

I tried

std::ostream cout = std::cout;

But I get

function "std::basic_ostream<_CharT, _Traits>::basic_ostream(const std::basic_ostream<_CharT, _Traits> &) [with _CharT=char, _Traits=std::char_traits<char>]" (declared at line 391 of "/usr/include/c++/5/ostream") cannot be referenced -- it is a deleted function

Please suggest.

like image 842
Thomas Kowalski Avatar asked Nov 28 '22 16:11

Thomas Kowalski


2 Answers

Sure, with a using declaration:

using std::cout;

Usual health warnings about not doing this in header files, and limiting it to small scopes apply.

like image 93
juanchopanza Avatar answered Dec 18 '22 07:12

juanchopanza


You can't copy streams (think about it, it just doesn't make sense), but you can get a reference to them:

std::ostream& my_cout = std::cout;

However, I would strongly advice you not to do so. If you see in some code std::cout you can be almost 100% certain that you know what it is. On the other hand a cout alone you should already look suspicious to you and a my_cout could really be anything. I know it is hard, but get used to type std::, on the long run it will help you more than you need time to type those 5 letters.

like image 38
463035818_is_not_a_number Avatar answered Dec 18 '22 07:12

463035818_is_not_a_number