I ran into some trouble trying to inherit std::ostream
and using a custom operator <<
which is basically doing some work and then forwarding to std::ostream <<
, e.g.:
#include <iostream>
#include <ostream>
struct ostream : std::ostream{
using std::ostream::ostream;
template<typename T>
ostream &operator <<(T &&arg){
//some work...
static_cast<std::ostream&>(*this) << std::forward<T>(arg);
return *this;
}
};
int main(){
ostream cc(std::cout.rdbuf());
cc << "hello world";
//cc << "hello world" << std::endl; //couldn't deduce template parameter `T`
}
The problem is when using manipulators, like in the line I have commented out, gcc complains about [template argument deduction/substitution failed:].
Do I have to set the template type explicitly?, if so how?, because I cannot use the in class std::ostream::operator <<
due to incompleteness.
Edit
I have just defined the custom operator <<
as a free function so not inside the class ostream
#include <iostream>
#include <ostream>
struct ostream : std::ostream{
using std::ostream::ostream;
};
template<typename T>
ostream &operator <<(ostream &os, T &&arg)
{
static_cast<std::ostream&>(os) << std::forward<T>(arg);
return os;
}
int main(){
ostream cc(std::cout.rdbuf());
cc << "hello world" << std::endl;
}
and it is working as expected, also for manipulators. Not sure why this makes a difference here, maybe someone could clarify this for me