I want to enforce explicit conversion between structs kind of like native types:
int i1;
i1 = some_float; // this generates a warning
i1 = int(some_float): // this is OK
int i3 = some_float; // this generates a warning
I thought to use an assignment operator and copy constructor to do the same thing, but the behavior is different:
Struct s1;
s1 = other_struct; // this calls the assignment operator which generates my warning
s1 = Struct(other_struct) // this calls the copy constructor to generate a new Struct and then passes that new instance to s1's assignment operator
Struct s3 = other_struct; // this calls the COPY CONSTRUCTOR and succeeds with no warning
Are there any tricks to get that third case Struct s3 = other_struct;
construct s3 with the default constructor and then call the assignment operator?
This all compiles and runs as it should. The default behavior of C++ is to call the copy constructor instead of the assignment operator when you create a new instance and call the copy constructor at once, (i.e. MyStruct s = other_struct;
becomes MyStruct s(other_struct)
; not MyStruct s; s = other_struct;
. I'm just wondering if there are any tricks to get around that.
EDIT: The "explicit" keyword is just what I needed!
class foo {
foo(const foo& f) { ... }
explicit foo(const bar& b) { ... }
foo& operator =(const foo& f) { ... }
};
foo f;
bar b;
foo f2 = f; // this works
foo f3 = b; // this doesn't, thanks to the explicit keyword!
foo f4 = foo(b); // this works - you're forced to do an "explicit conversion"