Say I have a class, that wraps some mathematic operation. Lets use a toy example
class Test
{
public:
Test( float f ) : mFloat( f ), mIsInt( false ) {}
float mFloat;
int mInt;
bool mIsFloat;
};
I’d like to create an operator overload with the following prototype:
float operator=( const Test& test )
{
if ( !test.mIsFloat ) return *this; // in this case don't actually do the assignment
return test.mFloat; // in this case do it.
}
So my questions are: can I overload operator= with a built-in return type?
and if so, is there a way to refer to the built-in type?
I know I could do this if I wrapped the built-ins with a class. But in this case I want to have the assignment operator work with built-in types on the LHS
Example of usage:
Test t( 0.5f );
float f = t; // f == 0.5
int i = 0;
i = t; // i stays 0.
UPDATE: Thanks so much for the help. Expanding a little bit from the toy example so people understand what I’m really trying to do.
I have a configuration system that allows me to get config parameters from a tree of parameters with different type ( they can be integers, floats, strings, arrays etc. ).
I can get items from the tree with operations like this:
float updateTime = config["system.updateTime"];
But it is possible that “system.updateTime” does not exist. Or is of the wrong type. Generally for configuration I have a block of defaults, and then code to overide the defaults from the config:
float updateTime = 10;
const char* logFile = "tmp.log";
... etc etc...
I want to do something like:
updateTime = config["system.updateTime"];
Where the operation succeeds if there is an override. So generally the assignment doesn’t happen if the return from operator[] is an “invalid” node in the tree.
Right now I solve it with a function like:
getConfig( config, "system.updateTime", updateTime );
But I would prefer to use assignment operator.
I could do this if I were willing to create classes to wrap the builtins.
class MyFloat
{
operator=( const Test& test ) { if (test.isValidNode() ) f = test.float(); return *this; }
float f;
}
But obviously it would be prefereable not to wrap built-ins with trivial classes just to overload assignment. Question is – is this possible in c++?
Based on your example, what you really want is an implicit conversion operator:
If you want to conditionally do the assignment, then you need to take another approach. A named method would probably be the best option, all things considered… something like this:
Whatever you do, be careful that the syntactic sugar you introduce doesn’t result in unreadable code.