Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use std::endl in a custom std::ostream class

Tags:

c++

std

templates

I am creating a custom ostream class which is briefly exposed in the following snippet. I would like to be able to use std::endl but the compiler does not let me. I don’t understand why.

#include <iostream> 

struct Bar
{
};

template <typename T>
struct Foo
{
};

template <typename T, typename U>
Foo<T>& operator<<(Foo<T>& _foo, U&&)
{
  return _foo;
}

int main()
{
  Foo<Bar> f;
  f << "aa" << std::endl;
}

The error gcc 4.7.1 gives me is:

main.cpp:21:21: error: no match for ‘operator<<’ in ‘operator<< ((* & f), (*"aa")) << std::endl’ main.cpp:21:21: note: candidates are: main.cpp:13:9: note: template Foo& operator<<(Foo&, U&&) main.cpp:13:9: note: template argument deduction/substitution failed: main.cpp:21:21: note:
couldn't deduce template parameter ‘U’

Why can’t it deduce parameter U? Shouldn’t this be typeof(std::endl) ?

like image 654
qdii Avatar asked Sep 12 '25 05:09

qdii


1 Answers

Since std::endl is

namespace std {
template <class charT, class traits>
basic_ostream<charT,traits>& endl(basic_ostream<charT,traits>& os);
}

Your class is not derived from basic_ostream, so it cannot work.

And basic_ostream has

basic_ostream<charT,traits>& operator<<
(basic_ostream<charT,traits>& (*pf)(basic_ostream<charT,traits>&))

for works with manipulators like std::endl.

like image 167
ForEveR Avatar answered Sep 13 '25 20:09

ForEveR