The issues:
1) If the view
function is defined as:
void view(std::ostream output, std::string text) // (1)
{
output << text;
}
And used:
view(std::cout, "Hello, World!"); // (2)
Then an error message is given by the compiler:
In MSVC:
error C2280: 'std::basic_ostream<char,std::char_traits<char>>::basic_ostream(const std::basic_ostream<char,std::char_traits<char>> &)': attempting to reference a deleted function
GCC:
error: use of deleted function 'std::basic_ostream<_CharT, _Traits>::basic_ostream(const std::basic_ostream<_CharT, _Traits>&) [with _CharT = char; _Traits = std::char_traits<char>]'
Clang:
error: call to deleted constructor of 'std::ostream' (aka 'basic_ostream<char>')
2) For the declaration
std::ostream os;
The following error message is displayed:
MSVC:
error C2512: 'std::basic_ostream<char,std::char_traits<char>>': no appropriate default constructor available
GCC:
error: 'std::basic_ostream<_CharT, _Traits>::basic_ostream() [with _CharT = char; _Traits = std::char_traits<char>]' is protected within this context
Clang:
error: calling a protected constructor of class 'std::basic_ostream<char>'
The reason:
This is all according to the specification of std::basic_ostream
There is no definition for a default constructor - so a variable of the type std::ostream
cannot be created, without specific constructor parameters.
And as C++ Reference says about the std::basic_ostream copy constructor:
The copy constructor is protected, and is deleted. Output streams are not copyable.
Explanation:
1) So the problem is that in (2)
the parameter std::cout
is been passed to a function which is defined in (1)
to copy the std::ostream
to the variable output
.
But the definition of the class says that the copy constructor cannot be used, so the compiler gives an error message.
2) In the case of creating the variable os
- it is not giving any constructor parameters, there is no default constructor, so the compiler gives an error message.
How to fix this?
1) In the declaration of the function change the definition to take a reference (&
) of std::ostream
as a parameter:
void view(std::ostream& output, std::string text) // (1)
This allows it to use the original object instead of making a copy (which the copy is not allowed).
2) If a variable is required, then also a reference should be used;
std::ostream& out = std::cout;