嵌套的重载操作符
nested overloaded operators?
可以嵌套重载操作符吗?我想筑巢<<Inside a ()
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;
}
};
你能帮我吗?恐怕我的例子对你来说不够真实,如果你还有疑问,请问我。真诚。
我真的不知道你在问什么,但我假设你的意思是写一个类传递给operator<<
的ostream&
。首先,您必须找到一种将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);
}
};
很抱歉我误解了你的问题。
我能想到的最好的方法是让operator<<
返回一个特定的类型,然后重载operator()
以接受该类型:
#include <cstdio>
namespace {
struct Foo {
struct Bar {
int i;
};
Foo& operator()(const Bar& b)
{
std::printf("bar, %dn", 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("foon");
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);
}
至少可以说,这不是一个常见的习语。