Comparing Function Pointers in Stream Class - c++

I'm trying to write my own stream class. It will do something with the input and pass it on to std::cout. So far I passed functions operating on the stream (e.g. std::endl) on to cout. Now, I want to check for std::endl input and perform some actions, if it occurs. I have implemented the behaviour like this
DebugStream& DebugStream::operator<< (ostream& (*pfun)(ostream&))
{
if(pfun == std::endl)
{
// do something
}
pfun(cout);
return *this;
}
Which results into
/path/to/file.cpp:89:24: error: assuming cast to type ‘std::basic_ostream<char>& (*)(std::basic_ostream<char>&)’ from overloaded function [-fpermissive]
using the GCC compiler. I don't know, how to compare the function pointer against the std::endl function. Maybe this problem is related to the template nature of the std::endl function? Or because it's inline?

The reason you get a warning is that std::endl is a template function. You can fix this error by forcing a comparison to a template instance of a particular type through a cast, like this:
typedef ostream& (*io_manip_ptr_t)(ostream&);
void demo(io_manip_ptr_t pfun) {
if (pfun == (io_manip_ptr_t)&endl) {
cout << "Hi" << endl;
}
}
Demo.
Note: Even though the work-around is available, this is only a workaround, not a solid solution, because comparing function pointers to decide on functionality introduces a very serious problem: your functions get reduced to an enum, so your code becomes impossible to extend from the outside.

Related

what's the data type of a string inside the double quote in c++

void main() {
cout << "Hello World" << endl;
}
I'm not allowed to make any change to the above main function while the output on the screen need to be sth like:
initialize
Hello World
clean up
My thought is that I need to use overloading operator of << . However I need to know what's the data type of the double quoted string following the operator << , otherwise I will not make full use of my redefined << operator. Anyone any thought?
The type of the literal is "array of {suitable number of} const chars", but a better approach might be to have some kind of global object.
(Adding an overload for the array would probably not even work, because the existing overload for char const * would be getting in the way.)
You could redefine std::ostream& operator<< (std::ostream&, const char*). There's one huge problem with this approach: It is undefined behavior. The standard library already defines that function, and you are not allowed to redefine standard library functions.
The key to solving this problem is to recognize that cout is in the global namespace. The solution is simple: Write your own class that overloads operator<< and make a global variable named cout that is an instance of this class. That way you are not running into undefined behavior.
You'll also need to do something with that endl that is in the global namespace.
Your code should look something like
// Insert your code here.
int main () {
cout << "Hello World" << endl;
}
Since this looks like homework, I'll leave the rest up to you.
The type of a string literal is char const[n] where n is the number of characters in the string literal, including the terminating null character. Note, however, that the solution to your problem isn't overloading operator<<(). Instead, you should look at constructors, destructors, and variable with static live-time.

Why we don't use format specifiers with cout?

When we use printf then we use format specifiers (such as %c,%p) but when we use cout we don't use them why and what is being done in background because which we are not using them ?
I know they are used in differently in c and c++ but still i want to know how formatting is being done in cout, while it is done in printf through format specifiers.
In C++ the ostream::operator<< is overloaded for different types. You can try and dig through your standard library implementation to see exactly what it looks like, but it will boil down to something that is approximately equivalent to the following:
class ostream
{
public:
ostream& operator<<( int val );
ostream& operator<<( float val );
ostream& operator<<( const char* val );
};
A real implementation will be much more complicated than the above, but that is roughly the idea. The hope was that this implementation would be more efficient than printf because the compiler could more easily inline code when appropriate. Consider the following:
int val = 0;
printf("%d\n", val);
std::cout << val << std::endl;
In the case of the printf a naively compiled program (one compiled by a compiler with no knowledge of format specifiers) would have to do the parsing of "%d\n" at runtime. Contrast that with the std::cout call, in which case the compiler merely needs to figure out which overload to use, and can then inline the code.
That said, there is nothing in the c standard that says a compiler can't parse the format specifiers at compile time if they are available. In practice the performance difference between a c style logging library using format specifiers and c++ ostreams is... nuanced.
Because printf is properly designed and cout has nasty internal state. With printf, the way you want each argument formatted is explicit in the format string; there is no hidden state. With cout, you can also control formatting (things like field width, etc.), but it's a hidden state inside the iostream object. If the previous user of the stream has left it in a non-default state, you'll do the wrong thing unless you explicitly reset the state. You don't even want to think about what happens in multi-threaded usage cases...
Basically the answer is operator overloading. Functions can have the same name as long as they take different parameters. operator<< is the function name you're wondering about. The compiler knows the type of what you're trying to print out, and calls the correct operator<<.
This is why if you create your own object you can't just write std::cout << yourObject; and expect it to work how you'd probably like it to. You have to specify how it should be printed,
ostream& operator<<(ostream& os, const YourObject& rhs) {
os << rhs.member;
return os;
}
But, happily, that's already been done for you behind the scenes in the case of something like an int. See: http://en.cppreference.com/w/cpp/io/basic_ostream/operator_ltlt2 for a full list of provided overloads.

Why is "out" used instead of "cout" when overloading the "<<" operator?

I am learning operator overloading. "out" is being used instead of "cout" when overloading "<<" operator. I don't understand why.
ostream &operator<<( ostream &out, const IntList &L ) {
out << "[ ";
for (int k=0; k< L.numItems; k++) {
out << L.Items[k] << ' ';
}
out << ']';
}
I want to ask differences between cout and out and what happens if I use cout instead of out.
Thanks for answers.
What you are looking at is a overloaded "stream insertion" operator, allowing some custom class to be written to an ostream object using the typical cout << myObject syntax.
The variable in this case is called out because that's the name they've given to the ostream object being passed into the function, which may be any output stream, whether it's cout or an fstream or a stringstream. It's just a variable name, and they could have called it blah and written:
ostream &operator<<( ostream &blah, const IntList &L ) {
blah << "[ ";
// ...
}
Typically you choose a variable name which is descriptive, and out as a name for an output stream is pretty descriptive.
cout would be an especially bad variable name, as it is strongly associated with std::cout, used for writing specifically to the standard output stream. This code doesn't write specificially to standard output, it writes to any ostream object via the << operator so they've chosen a more generic name for their ostream argument.
I want to ask differences between cout and out and what happens if I use cout instead of out. Thanks for answers.
In this case, an ostream& (out) is a parameter passed to the function. This allows the operator<< to work on any ostream.
cout is a specific ostream instance - the standard output stream. If they used cout here, you wouldn't be able to use the << operator on cerr (the standard error stream) or any other ostream. If you replaced the out with cout in the body, any time you used this on a different ostream, it'd be written to cout. (Of course, if you changed the parameter to be named cout, that wouldn't happen - but it would be very misleading to anybody looking at this code, as people would expect that the code writes to the standard output stream, not to the stream being passed in.)
In general, you only would want to use cout as a name if you are specifically referring to std::cout - the standard output stream, as using it in other contexts would be very confusing.
out is the name of the ostream object passed to the overloaded operator (inside the implementation of the operator).
The overloaded operator allows you to write code like this
IntList i;
cout<<i;
or
cerr<<i;
In the implementation if you substituted out with cout, then the second call
cerr<<i;
would print to standard output whereas it should have printed to standard error.
The critical thing here is really the types in the function signature: as long as it's a freestanding function with two parameters - one of type std::ostream& and the other able to be matched by the value to be streamed, then the function body will be invoked. It should return a reference to the stream to allow chaining (as in if (cout << firstIntList << secondIntList)).
The actual parameter names are whatever you feel like, as long as they're not reserved words. I tend to use "os", as in output-stream.

Overloaded operator<< for ostream syntax

I hav been going over some old hw assignments from a class last semester.
This was a given print function to print out linked list objects.
I don't understand why the overloaded operator takes two parameters and one being an
os object. When we were printing out actual linked list objects on main.cpp, we didn't
need to pass an os object. Also, why is it returning os? Why can't we just use cout
instead of "os <<" ?
Thank you!
template <class T>
void List<T>::print(ostream & os) const
{
os << "<";
ListNode * curr = head;
while (curr != NULL) {
os << " " << curr->data;
curr = curr->next;
}
os << " >";
}
// overloaded operator<<
template <class T>
ostream & operator<<(ostream & os, const List<T> & list)
{
list.print(os);
return os;
}
By the way the question was asked and how basic it is, I'm going to try to give a very simplistic (albeit rather informal and not so pedantic) answer.
I don't understand why the overloaded operator takes two parameters
and one being an os object
operator<< is a binary operator. It has a left-hand side and a right-hand side. When you write:
cout << 123;
You are invoking this operator with two operands (arguments): 'cout' on the left and an integer, '123', on the right.
When we were printing out actual linked list objects on main.cpp, we
didn't need to pass an os object.
Your print function is a member function or operator of a class. That would implicitly deduce that the first argument, crudely speaking, does not need to be explicitly passed since you already have the 'this' pointer to work with for your list object. That's not the case with non-member operators as you don't have an implicitly deduced 'this' object to work with already for the left-hand side operand.
When you write code like this:
my_list.print(cout);
You can think of it as actually passing in two arguments, 'my_list' and 'cout'. Even though you don't write it explicitly, you have access to 'my_list' through 'this' along with its members. That's not the case if you wrote the print function as a non-member, like so:
template <class T>
void print(const List<T>& my_list, ostream& os);
That's also the case with your operator which is not a member function.
Also, why is it returning os?
Returning a reference to ostream is what allows us to write statements like this:
cout << "hello " << "world";
First we invoke operator<<(cout, "hello ") which then gives us another ostream reference to work with which then allows us to proceed to invoke operator<<(cout, "world"). If it returned void, for example, it would not allow us to invoke that operator twice in one statement since we'd be trying to output "world " with void as the left-hand operand.
Why can't we just use cout instead of "os <<" ?
cout basically implements the ostream interface. So does ofstream, ostringstream, and other types of output streams. By writing it in terms of the basic interface required and not some specific ostream derivative, you allow the code you write to work with stdio streams, file streams, stream streams, and others. Basically it makes your code very general and reusable which is something you should strive to do when practical. You'll learn about this subject more as you tackle the concept of polymorphism.
Because it is a global non-member function. With the member function version, the first parameter is implicitly the invoking object, this. That means that your class always has to be on the left hand side. With the non-member function, it's an explicit parameter; this way, you can specify any type you want, and overload operators for classes that you can't modify the source for (as long as at least one parameter is a user-defined type).
The reason why you use os is so that it works with file streams and everything (anything that inherits from ostream), instead of just cout.
It returns os so that you can do more operator<< calls on the return value. This enables operator chaining, like w << x << y << z, which is the same as operator<<(operator<<(operator<<(w, x), y), z). If you return void or something, you would have to stop at w << x because you can't do anything with the return value of void.
I don't understand why the overloaded operator takes two parameters and one being an os object. When we were printing out actual linked list objects on main.cpp, we didn't need to pass an os object.
Yes you did: when you say cout << x, you are passing cout and x to operator<<.
Also, why is it returning os?
To make cout << x << y possible. This is parsed as (cout << x) << y, i.e. it inserts y into the return value of cout << x.
Why can't we just use cout instead of "os <<" ?
Because sometimes you want to output to another stream than standard output.
When we were printing out actual linked list objects on main.cpp, we
didn't need to pass an os object.
Yes, you did.. something like cout << obj;, where cout is the os output stream.
Also, why is it returning os? Why can't we just use cout instead of "os <<" ?
This allows chaining: cout << obj << " " << obj2;
Why can't we just use cout instead of "os <<" ?
That would hard-wire the output stream, so you couldn't write to file or any other output.

Function References

So I was just working with function pointers and I remembered that you could do this:
void Foo()
{
}
int main()
{
void(& func)() = Foo;
func(); //::Foo();
}
The obvious advantage being that references reference valid objects (unless they're misused), or functions in this case.
The obvious disadvantages being that you can't store an array of references and can't use them for member function pointers (at least as far as I can tell).
My question: does anyone use them (i.e., function references, not function pointers), and if so, in what scenarios have you found them useful/helpful?
The only place I can see them being useful off the bat is binding a reference to a certain function when working with conditional compilation.
I've used them before to add customization to classes by passing them to the constructor in a way like the strategy pattern
Function references, unlike function pointers, make it harder to create them from an invalid source. This is useful if you are making a wrapper around a C library - the C++ code can take a callback function by reference and pass the pointer to the C library if the lbrary requires that the passed pointer must not be NULL.
It is also a convenient way to alias a function, especially in C++11 with the new auto keyword:
#include <iostream>
#include <typeinfo>
void f(int i, char c)
{
std::cout << i << ' ' << c << std::endl;
}
int main()
{
std::cout << typeid(f).name() << std::endl; //FvicE
f(0, '1');
void (*pf)(int, char) (&f); //ugly
std::cout << typeid(pf).name() << std::endl; //PFvicE
(*pf)(2, '3');
pf(4, '5'); //works, but I don't recommend it
void (&rf)(int, char) (f); //still ugly
std::cout << typeid(rf).name() << std::endl; //FvicE
rf(6, '7');
auto &af (f); //pretty, but only works in C++11
std::cout << typeid(af).name() << std::endl; //FvicE, same as above
af(8, '9');
}
I think your example usage is quite good. Because if you would use an ordinary function pointer, and you then apply the address-of operator, you would get the address of the function pointer. Using a reference to function will do the expected thing, in that it returns a pointer to the function itself.
I also can't think of many examples. Keeping function references, as you point out, has some ugly consequences. Another possibly unwanted consequence is, if kept as a class-member, your objects will be non-assignable if you don't write your own operator= and refrain from trying to re-assign the function-reference.
I think most uses of function references are implicit, much like most uses of array-references - although much more so, when you accept arguments by-reference:
template<typename T>
void do_something(T const& t) { ... }
While accepting arrays by reference has the advantage of not losing their size information, accepting functions by reference explicitly doesn't seem to have an advantage (at least as far as I can see). I suppose the existence of function references largely is justified by the idealistic view of a reference as an alias-name of some object or function, together with the fact that it allows passing functions to such templates that accept their argument by reference.
I would probably avoid using them if I wouldn't need them inevitably. Constant function pointers also provide non-reassignable callables, and will probably avoid confusions when other programmers, who possibly are not very familiar with this language niches, read your code. Worth to note that Vandervoorde & Josuttis also recommend to avoid them to reduce confusion (in their book C++ Templates - The Complete Guide).
in addition to the use as strategy (as pointed out by Robert Gould), I freqently use them at the entrance point to (template) metaprogramming. A function reference can easily be picked up by a template parameter; from this point on it can be passed through several layers of (metaprogramming) templates. Of course, this holds true for a function pointer as well, but the reference is an alias and thus communicates the intention more clearly.
To give an example: when writing a generic command dispatching system for an application, a lot of different operations need to be announced as commands. We can use a simple "builder function" as front-end for the client code. Behind the scenes, this builder function picks up the actual function signature as template parameter, derives (by template metaprogramming) the actual parameter and return type values and possibly picks the suitable specialisation to store a "memento" and an "undo functor". These functors can than be stored either as function pointers internally, or using boost or tr1 or C++11 function objects. This way, it is possible to build a type safe command invocation and "undo" system.
I've used them in a plug-in system where plug-in DLLs could be loaded/unloaded at run-time. I would look for known symbols in each DLL and cast them to function pointers.