I am trying to understand why including iosfwd would cause output streams including standard strings not to work.
// hc_list.h file
#ifndef HC_LIST_H
#define HC_LIST_H
#include <cstdlib>
#include <iosfwd> // including this file makes the output operator throw errors
#include <list>
template <typename T>
class hcList
{
private:
std::list<T> selfList ; // a single internal STL list to hold the values
public:
hcList(void) {} ;
~hcList(void){} ;
template <typename U> friend std::ostream& operator<<(std::ostream &, const hcList<U> &) ;
} ;
template <typename U>
std::ostream& operator<<(std::ostream &out, const hcList<U> &outList)
{
out << "test" << std::endl ; // this line throws two errors, stated below
return out ;
}
#endif // HC_LIST_H
This code is included in the main.cpp file, where the main function is below:
// main.cpp file
#include <iostream>
#include "hc_list.h"
int main()
{
std::cout << "Begin Test" << std::endl;
return 0;
}
In order to actually utilize this code and generate the error, an empty cpp file is needed that includes the list header file.
// anyNamedFile.cpp file
#include "hc_list.h"
When I attempt to compile, I receive the following errors:
error: no match for 'operator<<' in 'out<< "test"'
error: 'endl' is not a part of 'std'
What is it in that causes the std namespace to get screwed up and no longer allow me to output strings?
You have two problems here. The first problem is that you are using
std::endl, but that is defined in<ostream>, which is not included.The second problem is that you are only including the header
<iosfwd>, which forward declares many of the iostream types. Forward declaration lets the compiler know that the types exist. However, you are trying to use these types’ functionality. Since you are doing that, you should include<ostream>, rather than<iosfwd>.<ostream>containsstd::endl, so that should take care of everything.