2011-08-26 142 views
0

嵌套重载操作符可能吗?我想窝< <内()嵌套重载操作符?

template<class T> 
struct UnknownName 
{ 
    T g; 
    T&operator<<(std::ostream&os, const T&v){return os<<v;} 
    bool operator()(const T&v) 
    { 
     if(v==g) 
     //do the streaming << then return true 
     else return false; 
    } 
}; 

你可以帮我吗?恐怕我的例子对你来说已经不够了,请问你是否还有疑问。真诚。

+0

你必须将你的'operator <<'作为非成员函数在类之外。 –

+2

'operator <<'是一个二元运算符,所以你的例子有太多的参数('std :: ostream','const T&'和接收者对象'UnknownName '。你想调用'operator <<'''Unknown''object或'const T&'参数? – Dawson

回答

0

我能想到的办法是有operator<<返回一个特定的类型,然后最好超载operator()接受类型:

#include <cstdio> 

namespace { 
    struct Foo { 
     struct Bar { 
      int i; 
     }; 

     Foo& operator()(const Bar& b) 
     { 
      std::printf("bar, %d\n", b.i); 
      return *this; 
     } 

     // obviously you don't *have* to overload operator() 
     // to accept multiple types; I only did so to show that it's possible 
     Foo& operator()(const Foo& f) 
     { 
      std::printf("foo\n"); 
      return *this; 
     } 
    }; 

    Foo::Bar operator<<(const Foo& f, const Foo& g) 
    { 
     Foo::Bar b = { 5 }; 
     return b; 
    } 
} 

int main() 
{ 
    Foo f, g, h; 
    f(g << h); 
    f(g); 
} 

这不是一个常见的成语,至少可以说。

1

我真的不知道你在问什么,但我认为你的意思是写一个类ostream&传递给operator<<。首先,您必须设法将T转换为字符串表示形式。我会假设功能TToString这样做。

template<class T> 
struct UnknownName 
{ 
    T g; 

    bool operator()(const T&v) 
    { 
     if(v==g) { 
     cout << v; 
     return true; 
     } 

     return false; 
    } 

    friend std::ostream& operator<<(std::ostream& os, const T& v) { 
     return os << TToString(v); 
    } 
}; 

对不起,如果我误解了你的问题。

+0

你不应该需要实现'TToString'。只要'operator <<'被定义为'T'类型,使用'os < Dawson

+0

@Toolbox这是为'T'定义'operator <<'所以你必须把'T'变成字符串,所以你不会得到无限递归。 –

+0

啊gotcha,傻了我。 – Dawson