1

I am having issue when trying to pass a reference object inside std::optional as a function argument.Does it not support storing reference objects ? Example -

void fun(std::optional<ClassA& obj>)

What exatly does this error mean - static_assert failed due to requirement '!is_reference

static_assert(!is_reference_v<_Tp>)

code4fun
  • 2,661
  • 9
  • 25
  • 39

1 Answers1

3

The cpp reference states quite clearly:

There are no optional references; a program is ill-formed if it instantiates an optional with a reference type. Alternatively, an optional of a std::reference_wrapper of type T may be used to hold a reference.

So use std:reference_wrapper as suggested.

Footnote: there are movement in the cpp commitee to enable references in std::optional. We might get them in future.

Croolman
  • 1,103
  • 13
  • 40
  • 1
    The other side of the argument is that there already *is* an optional reference: a pointer – Caleth Aug 16 '21 at 08:30
  • 1
    @Caleth: True, so `std::optional` is trivial to implement. It's about semantics, really: a `T*` is historically burdened with unclear ownership. A `std::optional` definitely does not own the object it references, and passing it to `delete` will give an error. – MSalters Aug 16 '21 at 09:21