Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I use static_cast<int&> to pass an integer reference parameter to a function in C++?

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?
like image 473
Gareth Avatar asked Mar 08 '13 17:03

Gareth


1 Answers

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)
like image 110
Kerrek SB Avatar answered Oct 16 '22 22:10

Kerrek SB