I have an enum parameter in a C++ program that I need to obtain using a function that returns the value through a parameter. I started by declaring it as an int but at code review was asked to type it as the enum (ControlSource). I did this but it breaks the Get() function - I noticed that a C-style cast to int& resolves the problem, but when I first tried to fix it with a static_cast<> it didn't compile.
Why is this, and why is it that when eTimeSource was an int no casting is required at all to pass the integer by reference?
//GetCuePropertyValue signature is (int cueId, int propertyId, int& value);
ControlSource eTimeSource = ControlSource::NoSource;
pPlayback->GetCuePropertyValue(programmerIds.cueId, DEF_PLAYBACKCUEPROPERTY_DELAY_SOURCE, static_cast<int&>(eTimeSource)); //This doesn't work.
pPlayback->GetCuePropertyValue(programmerIds.cueId, DEF_PLAYBACKCUEPROPERTY_DELAY_SOURCE, (int&)(eTimeSource)); //This does work.
int nTimeSource = 0;
pPlayback->GetCuePropertyValue(blah, blah, nTimeSource); //Works, but no (int&) needed... why?
When you convert a variable to a value of a different type, you obtain a temporary value, which cannot be bound to a non-constant reference: It makes no sense to modify the temporary.
If you just need to read the value, a constant reference should be fine:
static_cast<int const &>(eTimeSource)
But you might as well just create an actual value, rather than a reference:
static_cast<int>(eTimeSource)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With