使用运算符转发整个类

6 c++ templates

我想知道.我遇到了一个问题,这是一个小的重复.基本上我想转发一切.问题是,使用第一个<<会导致错误o<<1(或o<<SomeUserStruct().如果我包含第二个我得到的错误是不明确的.有没有办法我可以编写这个代码,以便它可以使用T&,否则它可以使用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();
}
Run Code Online (Sandbox Code Playgroud)

Naw*_*waz 10

template<typename T> FowardIt& operator<<(const T&t)
                                        //^^^^^ put const here
Run Code Online (Sandbox Code Playgroud)

进行参数const引用,如上所示.因为temporaries不能绑定到非const引用.您不需要定义另一个函数.只需制作参数const,问题就解决了.

如果您通过将函数const放在const最右侧来制作函数模板也会更好:

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
Run Code Online (Sandbox Code Playgroud)

如果这样做,那么你也可以在const对象上调用此函数:

void f(const FowardIt &o)//note: inside the function, o is an const object!
{
    o << 1;
    o << SomeUserStruct();
}
Run Code Online (Sandbox Code Playgroud)