Search code examples
c++referencepass-by-reference

How to accept both modifiable and non-modifiable arguments?


I have a debugging macro where I give it a float reference, and expect it to modify that variable sometimes, if it can.

#define probe(x) implProbe(#x##GETLINE, (x))

void implProbe(const char * loc, float & x){
    // this signature is a place holder
    ...
    x = 4.f;
}

However, I would also like to use the same macro for temporary variables or literals such as probe(1 + 2) or probe(x + y). The macro wouldn't need to have the same effect in those cases, I don't expect to see an output from it, I only want it to not break.

float var = 0.f;
probe(var);
// var == 4.f

var = 0.f;
probe(var + 2.f);  // this should be legal
// var == 0.f (didn't change)

probe(1.f); // this should be legal

Is there a way to accomplish this?


Solution

  • Implement two overloaded functions.

    void implProbe(const char * loc, float & x){
        ...
        x = 4.f;
    }
    void implProbe(const char * loc, const float & x){
        ...
    }