0

I have the following function

struct AlphaStore
{
  unsigned int alpha1;
  unsigned int alpha2;
}

struct Alpha
{
   int a=1;
   int b=2;
};


AlphaStore*  store;

const Alpha& myFunction1(int x)
{
 return reinterpret_cast<Alpha&> store->alpha1;
}

Now I would like to update the above myFunction1() to return null or nullopt or similar thing based on value x.

For example, is it possible to write

std::optional<const Alpha&> myFunction2(int x)
{
 return x? reinterpret_cast<Alpha&> store->alpha1 : nullopt;
}

If so how will I use reference on the return value?

For example, I would like to use auto* al = reinterpret_cast<const unsigned int*>(&myFunction1(arg));

How can I write this above statement if myFunction2() is used? Are there other alternative ways to return a null reference or something similar in this scenario?

  • 4
    Or simply have `myFunction2` return `const Alpha *`. That's more or less the definition of a pointer: something that is either a reference or null. – Nate Eldredge Mar 15 '22 at 22:15
  • 1
    Equivalently, the whole reason that references were invented was to have something that was like a pointer but could not be null. Wanting a "null reference" is a contradiction in terms. – Nate Eldredge Mar 15 '22 at 22:17
  • If `const Alpha *` is not an acceptable return type, it may benefit you to [edit] the question to explain why that return type won't work for you. – Drew Dormann Mar 15 '22 at 22:34
  • While not part of your question, it's also certainly Undefined Behavior if your returned `Alpha` is accessed, since it seems to be `reinterpret_cast` from an `unsigned int&`. – Drew Dormann Mar 15 '22 at 22:41
  • 4
    Does this answer your question? [std::optional specialization for reference types](https://stackoverflow.com/questions/26858034/stdoptional-specialization-for-reference-types) See comments of that question or use pointer – Sprite Mar 15 '22 at 23:00

0 Answers0