嵌套重载运算符?

时间:2011-08-26 22:35:01

标签: c++

是否可以嵌套重载运算符?我想嵌套<<在一个()

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;
   }
};
你能帮帮我吗?我担心我的例子对你来说是不真实的,请问你是否还有任何疑问。此致。

2 个答案:

答案 0 :(得分: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);
   }
};

很抱歉,如果我误解了你的问题。

答案 1 :(得分: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);
}

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