Forwarding an entire class using an operator

I am curious. I got into a problem, and here is a small permutation. In fact, I want to forward everything. The problem is that using the first <will result in an error with o<<1 (or o<<SomeUserStruct() ). If I turn on the second, I get errors in that it is ambiguous. Is there a way to write this code so that it uses T& when it can use T > otherwise?

 #include <iostream> struct FowardIt{ template<typename T> FowardIt& operator<<(T&t) { std::cout<<t; return *this; } //template<typename T> FowardIt& operator<<(T t) { std::cout<<t; return *this; } }; struct SomeUserStruct{}; int main() { FowardIt o; o << "Hello"; int i=1; o << i; o << 1; o << SomeUserStruct(); } 
+6
source share
1 answer
 template<typename T> FowardIt& operator<<(const T&t) //^^^^^ put const here 

Make the const parameter as shown above. Because temporary persons cannot be associated with a non-constant link. You do not need to define another function. Just enter const parameter, the problem will be solved.

It would also be better if you made a const function template by putting const in the far right of the function as:

 template<typename T> const FowardIt& operator<<(const T&t) const ^^^^^ ^^^^^ ^^^^^ | | | | | put const here as well | put const here | You've to make the return-type also const since it can't return non-const reference anymore 

If you do this, you can call this function on const objects as well:

 void f(const FowardIt &o)//note: inside the function, o is an const object! { o << 1; o << SomeUserStruct(); } 
+10
source

Source: https://habr.com/ru/post/891333/


All Articles