1

I tried to create generic stream class holder, but it seems like I cannot pass std::cout to it, the code:

#include <iostream>

struct x
{
    std::ostream &o;
    x(std::ostream &o):o(o){}
};

int main()
{
    x(std::cout);
    x.o<<"Hi\n";
    return 0;
}

fails when compiled as:

c++ str.cc -o str -std=c++11
str.cc: In function ‘int main()’:
str.cc:11:14: error: invalid use of qualified-name ‘std::cout’
str.cc:12:4: error: expected unqualified-id before ‘.’ token

Why?

Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
Draif Kroneg
  • 743
  • 13
  • 34
  • 4
    Did you mean `x someName(std::cout); someName.o << ...`? – Angew is no longer proud of SO Mar 23 '15 at 17:57
  • 2
    The reasoning for why that first line is an error should be the same as this: http://stackoverflow.com/questions/24623071/is-typex-valid. You can't use `x` like an object afterward anyway, though. `x.o` makes no sense since `x` is a type. – chris Mar 23 '15 at 17:58
  • As chris points out the answer that explains why it does not work but this looks like a typo as @Angew indicates. – Shafik Yaghmour Mar 23 '15 at 19:04

2 Answers2

6
x(std::cout);

is equivalent to

x std::cout;

which tries to declare a local variable called std::cout. That's not allowed.

If you wanted to declare a variable of type x, passing std::cout to its constructor, then that's

x x(std::cout);

although, for the sake of your sanity, it might be better to give it a different name to the class (and change the following line to use that name).

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
1

Use:

int main()
{
    x object(std::cout);
    object.o << "Hi\n";
    return 0;
}
R Sahu
  • 204,454
  • 14
  • 159
  • 270