C++ Logo

std-proposals

Advanced search

[std-proposals] [[opt_in]]

From: Jan Schultke <janschultke_at_[hidden]>
Date: Thu, 23 Jul 2026 10:49:12 +0200
What are your thoughts on adding an [[opt_in]] attribute for opting into
features explicitly?

The basis for the idea is Kotlin's @OptIn and @RequiresOptIn annotations. A
library author can require opt-in for features that are
experimental/nightly/unstable, and the user gets a compiler warning unless
they also opt into that feature using the @OptIn annotation.

This seems like something that could work just as well in C++, and is
vaguely similar to [[deprecated]], except that [[deprecated]] has no "opt
in" option (and deliberately so).

For the standard library, one possible use is to obsolete the practice of
putting TS features into namespace std::experimental. It could be replaced
with [[requires_opt_in(std::experimental)]] or something. The namespacing
is rather annoying for users because transitioning from the TS feature to
the standard feature once it gets merged is an API break. This does not
happen with an [[opt_in]] annotation, which might simply become unnecessary
at some point, without breaking any code. Here's how it would work:

namespace lib {
void stable();
[[requires_opt_in("unstable-stuff")]] void unstable();
}


int main() {
    stable(); // OK
    unstable(); // warning: requires opt-in 'unstable-stuff'
    [[opt_in("unstable-stuff")]] unstable(); // OK
}


Of course, you could make the [[opt_in]] less granular than individual
statements, like letting users opt in at a namespace or file level.

For reference, there are about 8K Kotlin files on GitHub
using @RequiresOptIn.
https://github.com/search?q=language%3AKotlin+%2FRequiresOptIn%2F+-is%3Afork&type=code

Another use case I envision is that it makes standard library vendors much
more willing to provide future standard extensions in older standards. For
example, you can have [[requires_opt_in(gnu::cxx26_extensions)]] on a
library declaration, which lets you omit a warning when a user tries to use
that declaration in C++23 mode or older.

Another use case is that this would let us "forever-deprecate" features
that we are not happy with or that we consider to have security flaws, but
which we cannot realistically remove. For example, one could have

[[requires_opt_in(std::low_quality_random)]] int rand();


Maybe it's not the best example, but I'm sure you can think of features
that we don't particularly like but don't want to deprecate because
complete removal is unrealistic.

Received on 2026-07-23 08:49:27