I am wondering. I hit a problem and here is a small repoduce. Essentially i want to forward everything. The problem is, using the first << will cause an error with o<<1 (or o<<SomeUserStruct(). If i include the second i get errors about it being ambiguous. Is there a way i can write this code so it will use T& when it can otherwise uses T?
#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();
}
Make the parameter
constreference, as shown above. Because temporaries cannot be bound to non-const reference. You don’t need to define another function. Just make the parameterconst, the problem will be solved.It would also be better if you make the function template
constas well by puttingconstto the rightmost side of the function as:If you do so, then you can call this function on
constobjects as well: