Reputation: 489
Is nesting overloaded operators possible ? I would like to nest << 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;
}
};
Would you please help me out ? I am afraid my example is unreal enough to you, please just ask if you still have any doubts. Sincerely.
Upvotes: 0
Views: 923
Reputation: 20047
The best I can think of would be to have operator<<
return a specific type, and then overload operator()
to accept that type:
#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);
}
This isn't a common idiom, to say the least.
Upvotes: 0
Reputation: 75150
I can't really tell what you're asking, but I assume you mean write a class to the ostream&
that gets passed to operator<<
. First you have to make up a way to convert a T
to a string representation. I'll assume the function TToString
does that.
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);
}
};
Sorry if I misinterpreted your question.
Upvotes: 1