I have the following code:
#include <iostream>
using namespace std;
ostream& f(ostream& os) {
return os << "hi";
}
int main() {
cout << "hello " << f << endl;
return 0;
}
And somehow this works - the output is "hello hi". How does this get interpreted by the compiler? I don't understand how a function can be inserted into a stream.
std::ostream has an operator<< overload that receives a pointer to a function with the signature such as the one you wrote (number 11 in this list):
basic_ostream& operator<<(
std::basic_ostream<CharT,Traits>& (*func)(std::basic_ostream<CharT,Traits>&) );
which just calls the given function passing itself as argument. This overload (along with several similar others) is there to allow you to implement stream manipulators, i.e. stuff that you output in the stream with an << and changes the state of the stream from there. For example, our version of the (incorrectly) ubiquitous std::endl may be implemented as
std::ostream &myendl(std::ostream &s) {
s<<'\n';
s.flush();
return s;
}
which can then be used exactly as the "regular" std::endl:
std::cout<<"Hello, World!"<<myendl;
(the actual implementation is templated and a bit more complicated because it has to work even with wide streams, but you got the idea)
std::ostream::operator<< has an overload which accepts a function as parameter; and the body of that overload is to invoke the function given.
This is exactly how endl works in fact. endl is actually a function similar to:
ostream &endl(ostream &os)
{
os << '\n';
os.flush();
return os;
}
Related
I was working on a function which looks like so:
inline std::ostream& mvUp(int n,std::ostream& ss){
char u[8];
sprintf(u,"\033[%dA",n);
ss<<u;
return ss;
}
and using it like so:
std::cout<<mvUp(1);
however it shows error:
std::cout<<mvUp(1);
| ^_____too few args in function call
^_______________no operator "<<" match these operands
I also tried: std::cout<<mvUp(1,std::cout); but still not working.
std::cout<<mvUp(1);
^_______________no operator "<<" match these operands
now when I try making it template,
template <int n>
inline std::ostream& mvUp(std::ostream& ss){
char u[8];
sprintf(u,"\033[%dA",n);
ss<<u;
return ss;
}
and use it: std::cout<<mvUp<1>, this works totally fine but the problem with this is that templates take const args.
Not able to figure out where am I getting wrong. Also how is it working in templates when I am not passing any args?
Modern C++ code uses std::string, and other classes. This makes implementing this kind of an overload trivial.
#include <string>
#include <sstream>
inline std::string mvUp(int n) {
std::ostringstream o;
o << "\033[" << n << "A";
return o.str();
}
Then, everything will work automatically:
std::cout<<mvUp(1);
Your mvUp returns std::string, and the existing << overload takes care of the rest.
The fact that std::ostream& mvUp(std::ostream& ss); std::cout << mvUp<1> works is not a peculiarity of C++ function call syntax.
std::cout has its operator<< overloaded to accept single-parameter functions like this one, and call them by passing itself as the first argument.
Given std::ostream& mvUp(int n,std::ostream& ss);, std::cout<<mvUp(1) doesn't work because your function doesn't have one parameter. And std::cout << mvUp(1,std::cout); doesn't work because your function returns std::ostream&, which can't be printed.
The generic solution is to make a class with overloaded operator<<. But, as the other answer suggests, here you can just make a function that returns std::string, and print its return value.
You are trying to create a custom ostream manipulator, similar to std::setw() and other manipulators from the <iomanip> library. But what you have written is not the correct way to implement that. Your manipulator needs to return a type that holds the information you want to manipulate the stream with, and then you need to overload operator<< to stream out that type. That will give you access to the ostream which you can then manipulate as needed.
Try something more like this:
struct mvUpS
{
int n;
};
mvUpS mvUp(int n) {
return mvUpS{n};
}
std::ostream& operator<<(std::ostream& ss, const mvUpS &s) {
return ss << "\033[" << s.n << "A";
}
Now std::cout << mvUp(1); will work as expected.
Demo
So I got stuck on a simple print-function today and I really don't know how to fix this problem. Basically I want to pass my Strings to a function in a std::cout-style like this:
foo(std::ostringstream() << "Hello" << " World!");
And from what I've read it should be possible by a function along the lines of
void foo(std::ostringstream& in)
but when implementing I get a somewhat strange behavior:
#include <iostream>
#include <sstream>
void foo(std::ostringstream& in)
{
std::cout << in.str();
}
int main()
{
std::ostringstream working;
working << "Hello" << " World!";
foo(working); // OK
std::ostringstream notWorking;
notWorking << "Hello";
foo(notWorking<<" World!"); // Not OK?!
return 0;
}
While the first call of foo seems fine and works like expected, the second one refuses to compile even though they should (from my perspective) be technically the same thing.
Error:
error C2664: 'void foo(std::ostringstream &)': cannot convert parameter 1 from 'std::basic_ostream<char,std::char_traits<char>>' to 'std::ostringstream &'
I'm using MS Visual Studio 2013 Express on Win7 x64
The overloads of shifting operators for IO operations take the base streams by reference. That is:
std::ostream& operator<<( std::ostream& os , foo myfo )
{
os << myfoo;
return os;
}
So use std::ostream instead of std::ostringstream as function parameter:
void f( std::ostream& stream );
It's simply because the second expression
notWorking<<" World!"
returns a std::ostream& not a std::ostringsream&.
The reason for your error is that you’re trying to implicitly downcast an ostream into an ostringstream because the result of the << operator is always ostream& regardless of the concrete string type. Changing foo() to take an ostream& ought to solve this, unless you need to rely specifically on ostringstream features in the implementation of foo, in which case you can dynamic_cast.
Also, by constructing a temporary ostringstream in your foo(std::ostringstream() << "Hello" << " World!"); example, you obtain an rvalue. foo() expects an lvalue reference to the stream. You might be able to get away with changing foo() to take an rvalue reference: std::ostream&&.
I don't understand what this ostream function declaration means:
ostream& operator<< (ostream& (*pf)(ostream&));
(specifically, the (*pf)(ostream&) part). I want to do something like:
void print(ostream& os){
cout << os;
}
but I get the error:
Invalid operands to binary expression ('ostream' . . . and 'ostream')
I don't understand what this ostream function declaration means:
ostream& operator<< (ostream& (*pf)(ostream&));
Have you seen functions like std::endl, std::flush, std::hex, std::dec, std::setw...? They can all be "sent" to a stream using "<<", then they get called with the stream as a function argument and do their magic on the stream. They actually match the ostream& (*pf)(ostream&) argument above, and that operator's the one that lets them be used. If we look at the Visual C++ implementation...
_Myt& operator<<(_Myt& (__cdecl *_Pfn)(_Myt&))
{
return ((*_Pfn)(*this));
}
...you can see if just calls the function, passing the stream it's used on as an argument. The functions are expected to return a reference to the same stream argument, so that further << operations may be chained, or the stream may be implicitly converted to bool as a test of stream state.
See http://en.cppreference.com/w/cpp/io/manip for more information about io manipulators.
You wanted help with:
void print(ostream& os){
cout << os;
}
The issue here is that you're sending the ostream argument to another stream - cout - and it doesn't know what you want it to do with it.
To send the current content of os to cout, try:
void print(ostream& os){
cout << os.rdbuf();
}
Or if you want to print some actual data to the stream represented by the argument:
void print(ostream& os){
os << "show this!\n";
}
print(std::cout); // to write "show this!\n" to `std::cout`
print(std::cerr); // to write "show this!\n" to `std::cerr`
What the declaration means.
The formal argument …
ostream& (*pf)(ostream&)
declares an argument named pf which is a pointer, to which you can apply an argument parenthesis with an ostream& argument, which constitutes a call that returns an ostream& as its result.
It can be simplified to just …
ostream& pf(ostream&)
where you can more easily see that it's a function.
The drawback is that this form is seldom used, so not everybody is aware that it decays to the first form (much the same as e.g. int x[43] as a formal argument type is effectively the same as just int x[] because both these forms decay to just int* x in the function type, so that in the function body you can even increment that x).
What it’s used for.
A function of the above form is usually an output stream manipulator. That means, you can pass it to the << output operator. What happens then is just that << calls that function, with the stream as argument, as specified by C++11 §27.7.3.6.3/1 and 2:
basic_ostream<charT,traits>& operator<<
(basic_ostream<charT,traits>& (*pf)(basic_ostream<charT,traits>&))
Effects: None. Does not behave as a formatted output function (as described in 27.7.3.6.1).
Returns: pf(*this).
There is also an overload of << that takes a similar function, but with std::basic_ios& argument and result, and one that takes a function with std::ios_base argument and result.
Class std::ios_base is the base of the iostreams class hierarchy and the standard manipulators defined at that level are …:
Format flag manipulators:
boolalpha, noboolalpha, showbase, noshowbase, showpoint, noshowpoint, showpos, noshowpos, skipws, noskipws, uppercase, nouppercase, unitbut and nounitbuf.
Adjustment field manipulators:
internal, left and right.
Numeral system base manipulators:
dec, hex and oct.
Floating point number presentation manipulators:
fixed, scientific, hexfloat and defaultfloat.
Manipulators that take user arguments don’t follow this form and those that the standard provides are in a separate header called <iomanip>.
Example: a user-defined manipulator.
Code:
#include <iostream>
#include <string>
// With Visual C++, if necessary define __func__ as __FUNCTION__.
using namespace std;
class Logger
{
private:
string funcname_;
static int call_level;
auto
static indent( ostream& stream )
-> ostream&
{ return (stream << string( 4*call_level, ' ' )); }
public:
Logger( string const& funcname )
: funcname_( funcname )
{
clog << indent << "-> " << funcname_ << endl;
++call_level;
}
~Logger()
{
--call_level;
clog << indent << "<- " << funcname_ << endl;
}
};
int Logger::call_level = 0;
#define WITH_LOGGING Logger logging( __func__ )
void c() { WITH_LOGGING; }
void b() { WITH_LOGGING; c(); }
void a() { WITH_LOGGING; b(); }
auto main() -> int { a(); }
Output, which shows the calls and returns, nicely indented:
-> a
-> b
-> c
<- c
<- b
<- a
The parameter portion of the declaration:
ostream& operator<< (ostream& (*pf)(ostream&));
is a function pointer syntax.
The expression:
ostream& (*pf)(ostream&)
Declares a pointer to a function, pf, that takes an ostream& parameter and returns a reference to an ostream.
If I declare a function:
ostream& my_function(ostream& output);
Then I can pass a pointer to the function as the parameter:
operator<< (my_function);
Read up on function pointer syntax. Search the web and stackoverflow.
What I mean:
Everyone knows this method of redirecting stream to output:
cout << "sometext"
but is it possible to pass that stream to a function like this:
my_function() << "sometext";
Yes*:
#include <iostream>
#include <ostream>
std::ostream & my_function() { return std::cout; }
// ...
my_function() << "Hello world.\n";
*) Nothing you said in words is entirely correct, and you may well struggle later integrate this into your project, but this answer shows how to make your code do what you want.
Everyone knows this method of redirecting stream to output:
That's not what that does. The stream is called cout; that's the iostream object. The << operator does not redirect anything. The std::ostream objects all have overloaded operator<< functions. Those functions are invoked when you use << with a stream on the left-hand side and some type that has an overload for it on the right.
<< "sometext" is not a "stream" that can be "redirected". It isn't even a valid expression in C++. The << operator is binary. it takes two parameters.
my_function() << "sometext"; can only work if it returns a std::ostream class or something derived from it. Or something that has an overloaded operator<< defined for it and const char*.
cout << "sometext"
This is not "redirecting stream to output" it is invoking the operator << function on the cout object with the string literal "sometext"
if my_function() is returning a ostream which has operator << overloaded then my_function() << "sometext" will compile else it will give an error.
If you are looking for a way to overload << for your own function unrelated to streams, here is how you can do it:
struct MyStruct {
void DoSomething(const string& s);
};
MyStruct &operator<<(MyStruct &x, const string& s) {
x.DoSomething(s);
return x;
}
MyStruct& my_function() {
return MyStruct;
}
int main() {
my_function() << "Hello, world!";
}
In this example, DoSomething will be called on the instance of MyStruct returned from my_function, and "Hello, world!" will be passed to it as an argument.
If I understand what you are asking about, the closest equivalent of a shell redirect for a function that uses std::cout for output is probably to switch temporarily std::cout's internal stream buffer for a different one.
Of course, this is inherently not thread safe and won't cope if the function itself expects std::cout and stdout to be the same underlying thing.
#include <iostream>
#include <sstream>
int main()
{
std::stringbuf redir( std::ios_base::out );
std::streambuf* save = std::cout.rdbuf( &redir );
my_function(); // cout output ends up in redir
std::cout.rdbuf( save ); // restore original cout
}
I'm trying to write my own logging class and use it as a stream:
logger L;
L << "whatever" << std::endl;
This is the code I started with:
#include <iostream>
using namespace std;
class logger{
public:
template <typename T>
friend logger& operator <<(logger& log, const T& value);
};
template <typename T>
logger& operator <<(logger& log, T const & value) {
// Here I'd output the values to a file and stdout, etc.
cout << value;
return log;
}
int main(int argc, char *argv[])
{
logger L;
L << "hello" << '\n' ; // This works
L << "bye" << "alo" << endl; // This doesn't work
return 0;
}
But I was getting an error when trying to compile, saying that there was no definition for operator<< (when using std::endl):
pruebaLog.cpp:31: error: no match for ‘operator<<’ in ‘operator<< [with T = char [4]](((logger&)((logger*)operator<< [with T = char [4]](((logger&)(& L)), ((const char (&)[4])"bye")))), ((const char (&)[4])"alo")) << std::endl’
So, I've been trying to overload operator<< to accept this kind of streams, but it's driving me mad. I don't know how to do it. I've been loking at, for instance, the definition of std::endl at the ostream header file and written a function with this header:
logger& operator <<(logger& log, const basic_ostream<char,char_traits<char> >& (*s)(basic_ostream<char,char_traits<char> >&))
But no luck. I've tried the same using templates instead of directly using char, and also tried simply using "const ostream& os", and nothing.
Another thing that bugs me is that, in the error output, the first argument for operator<< changes, sometimes it's a reference to a pointer, sometimes looks like a double reference...
endl is a strange beast. It isn't a constant value. It's actually, of all things, a function. You need a special override to handle the application of endl:
logger& operator<< (logger& log, ostream& (*pf) (ostream&))
{
cout << pf;
return log;
}
This accepts insertion of a function that takes an ostream reference and returns an ostream reference. That's what endl is.
Edit: In response to FranticPedantic's interesting question of "why can't the compiler deduce this automatically?". The reason is that if you delve yet deeper, endl is actually itself a template function. It's defined as:
template <class charT, class traits>
basic_ostream<charT,traits>& endl ( basic_ostream<charT,traits>& os );
That is, it can take any sort of ostream as its input and output. So the problem isn't that the compiler can't deduce that T const & could be a function pointer, but that it can't figure out which endl you meant to pass in. The templated version of operator<< presented in the question would accept a pointer to any function as its second argument, but at the same time, the endl template represents an infinite set of potential functions, so the compiler can't do anything meaningful there.
Providing the special overload of the operator<< whose second argument matches a specific instantiation of the endl template allows the call to resolve.
endl is an IO manipulator, which is a functor that accepts a stream by reference, performs some operation on it, and returns that stream, also by reference. cout << endl is equivalent to cout << '\n' << flush, where flush is a manipulator that flushes the output buffer.
In your class, you just need to write an overload for this operator:
logger& operator<<(logger&(*function)(logger&)) {
return function(*this);
}
Where logger&(*)(logger&) is the type of a function accepting and returning a logger by reference. To write your own manipulators, just write a function that matches that signature, and have it perform some operation on the stream:
logger& newline(logger& L) {
return L << '\n';
}
I believe that the problem is your stream doesn't overload operator<< to accept a function that has the same type as std::endl as illustrated in this answer: std::endl is of unknown type when overloading operator<<
In C++ it is the stream buffer that encapsulates the underlying I/O mechanisim. The stream itself only encapsulates the conversions to string, and the I/O direction.
Thus you should be using one of the predefined stream classes, rather than making your own. If you have a new target you want your I/O to go to (like a system log), what you should be creating is your own stream buffer (derived from std::streambuf).