views:

46

answers:

3

If I have these 2 constructors for MyClass:

MyClass(int n1);
MyClass(int n1, int n2);

and an overloaded (non-member) operator+:

MyClass operator+(MyClass m1, const MyClass& m2);

This enables me to write code like this:

MyClass m;
5 + m:

which I guess uses implicit cast through the defined constructor, correct?

Is there anyway to do this implicit cast with the constructor taking 2 arguments? With code looking something like this:

MyClass m;
{15, 8} + m:

?

Or maybe just do an explicit cast from {9, 4} to a MyClass-object?

+5  A: 

In a word, no. The most succinct option is MyClass(15,8) + m;.

Oli Charlesworth
+1  A: 

No, but you can construct in place:

MyClass m;
m + MyClass(15,8);
David Rodríguez - dribeas
A: 

I don't believe so, but why do you need it to be implicit rather than explicit? If you're going to have to use the bracket notation anyway, it's not something that could be generated from a single variable, so I don't believe there's any downside to simply saying:

myclass(15, 8) + m;

This will generate it on the stack, and produce the same result as an implicit cast.

Bryan