Date: Sun, 8 Nov 2026 19:40:03 -0800
Hi all,
The latest C++ draft (N5054) has the following wording in 22.5.3.1
[optional.optional.general]:
```
namespace std {
template<class T>
class optional {
public:
// ...
private:
union {
remove_cv_t<T> val; // exposition only
};
};
}
```
And 22.5.3.8 [optional.monadic]:
```
template<class F> constexpr auto and_then(F&& f) &;
...
Effects: Equivalent to:
if (*this) {
return invoke(std::forward<F>(f), val);
} else {
return remove_cvref_t<U>();
}
```
Note that the non-const `val` is passed to `f` directly and can be modified
here, e.g.
```
std::optional<const int> o(1);
o.and_then([](int& r) { r = 2; return std::optional<int>(r); }); // *o is
now 2
```
This seems to be a regression from C++23 since it's ill-formed in C++23. Is
this intended? Is this already reported?
To preserve the C++23's behavior, I think we should cast `val` back to T&,
e.g.
```
if (*this) {
return invoke(std::forward<F>(f), static_cast<T&>(val));
} else {
return remove_cvref_t<U>();
}
```
Thanks,
Tianjiao
The latest C++ draft (N5054) has the following wording in 22.5.3.1
[optional.optional.general]:
```
namespace std {
template<class T>
class optional {
public:
// ...
private:
union {
remove_cv_t<T> val; // exposition only
};
};
}
```
And 22.5.3.8 [optional.monadic]:
```
template<class F> constexpr auto and_then(F&& f) &;
...
Effects: Equivalent to:
if (*this) {
return invoke(std::forward<F>(f), val);
} else {
return remove_cvref_t<U>();
}
```
Note that the non-const `val` is passed to `f` directly and can be modified
here, e.g.
```
std::optional<const int> o(1);
o.and_then([](int& r) { r = 2; return std::optional<int>(r); }); // *o is
now 2
```
This seems to be a regression from C++23 since it's ill-formed in C++23. Is
this intended? Is this already reported?
To preserve the C++23's behavior, I think we should cast `val` back to T&,
e.g.
```
if (*this) {
return invoke(std::forward<F>(f), static_cast<T&>(val));
} else {
return remove_cvref_t<U>();
}
```
Thanks,
Tianjiao
Received on 2026-11-09 03:40:15
