Reputation: 22906
Is it possible to overload <<
operator such that this works?
void f (int f)
{
}
int main ()
{
f << 2;
}
What do I need to study for this to work?
Upvotes: 1
Views: 136
Reputation: 45665
If you want to make any call like
f << arg1 << ... << argN;
to behave the same as
f(arg1, ..., argN);
then the follwing C++11 code does what you want.
For every function you want to call like this, create a "proxy object" holding the arguments to be called on the function f
. This object should return a new "proxy object" which then requires one argument less. Nice side-effect: this can be used for argument currying.
Here is the full code with a running example: http://ideone.com/NFtnuT
In a nutshell, this code does the following: It defines a template class with variadic template arguments:
template<class R, /* ... */>
class ProxyFunction
{
// Underlying function:
std::function<R(/* ... */)> f;
public:
ProxyFunction(std::function<R(/* ... */)> f) : f(f) {}
ProxyFunction<R, /* one arg less */> operator <<(/* one argument */) {
/* create new proxy function with one argument less */
}
};
For the last argument, you should call the underlying function on either destruction or when casting to the return type R
. This is done by partially specializing the template class for the case where /*...*/
actually is nothing.
The code is then called as:
// Create proxy function. You can pass f around as you want.
auto f = makeProxy(/* underlying "real" function */);
// Call f using this syntax, discarding the result:
f << a << b;
// Use its result:
int result = f << a << b;
Now the nice thing about this is that it supports currying:
auto g = (f << a); // Bind first parameter, but don't call yet.
int result = (g << b); // Bind second parameter, now call it.
Upvotes: 3
Reputation: 153909
Overloading an operator is only legal if at least one of the operands has a user defined type (class type or enum). You could conceivably define something like:
?? operator<<( void (*f)( int ), MyType );
where MyType
is either an enum or a class type (but not an
int
), but do you want to? In C++, <<
has two established
meanings: formatting data (for eventual output), and left shift
(both of which imply state in the left hand operand).
Overloading the operator to do something unrelated is operating
overload abuse. When the reader sees a <<
, he has a right to
assume that some sort of formatting or shifting is going on.
Overloading <<
for something unrelated will confuse him.
Upvotes: 2
Reputation: 258568
f
needs to be an instance of a class with overloaded operator <<
, or it must return an object of a type with the overloaded operator (but you'd need to call it f()
).
struct F
{
F& operator << (int x) { return *this; }
};
//...
F f;
f << 2;
Upvotes: 2