开发者

forwarding an entire class with an operator

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 &l开发者_如何学Pythont;< 1;
    o << SomeUserStruct();
}


template<typename T> FowardIt& operator<<(const T&t)
                                        //^^^^^ put const here

Make the parameter const reference, as shown above. Because temporaries cannot be bound to non-const reference. You don't need to define another function. Just make the parameter const, the problem will be solved.

It would also be better if you make the function template const as well by putting const to the rightmost side 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 so, then 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();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜