Question

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?
Was it helpful?

Solution

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)

OTHER TIPS

static_cast<int&>((eTimeSource))); //This doesn't work.

Right, it doesn't work, because eTimeSource is not an int so you can't bind a int& to it.

(int&)((eTimeSource))); //This does work.

Wrong, that doesn't work either, it just appears to. The C-style cast lies to the compiler and says "just make it this type, even if that's not legal". Just because something compiles doesn't mean it works.

why is it that when eTimeSource was an int no casting is required at all to pass the integer by reference?

Because you can bind an int& to an int but not to a different type, and eTimeSource is a different type. An int& is a reference to an int. If you could bind it to a different type it wouldn't refer to an int, would it?

If the code reviewer said to change the variable to an enumeration type they probably also meant for you to change the function parameter to take a ControlSource&

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top