code
stringlengths
2.5k
150k
kind
stringclasses
1 value
cpp Standard library header <utility> Standard library header <utility> ================================= This header is part of the [general utility](../utility "cpp/utility") library. | | | --- | | Includes | | [<compare>](compare "cpp/header/compare") (C++20) | [Three-way comparison operator](../language/operator_comparison#Three-way_comparison "cpp/language/operator comparison") support | | [<initializer\_list>](initializer_list "cpp/header/initializer list") (C++11) | `[std::initializer\_list](../utility/initializer_list "cpp/utility/initializer list")` class template | | Namespaces | | `[rel\_ops](../utility/rel_ops/operator_cmp "cpp/utility/rel ops/operator cmp")` | Provide automatic comparison operators | | Defined in namespace `std::rel_ops` | | [operator!=operator>operator<=operator>=](../utility/rel_ops/operator_cmp "cpp/utility/rel ops/operator cmp") (deprecated in C++20) | automatically generates comparison operators based on user-defined `operator==` and `operator<` (function template) | | Functions | | [swap](../algorithm/swap "cpp/algorithm/swap") | swaps the values of two objects (function template) | | [exchange](../utility/exchange "cpp/utility/exchange") (C++14) | replaces the argument with a new value and returns its previous value (function template) | | [forward](../utility/forward "cpp/utility/forward") (C++11) | forwards a function argument (function template) | | [forward\_like](../utility/forward_like "cpp/utility/forward like") (C++23) | forwards a function argument as if casting it to the value category and constness of the expression of specified type template argument (function template) | | [move](../utility/move "cpp/utility/move") (C++11) | obtains an rvalue reference (function template) | | [move\_if\_noexcept](../utility/move_if_noexcept "cpp/utility/move if noexcept") (C++11) | obtains an rvalue reference if the move constructor does not throw (function template) | | [as\_const](../utility/as_const "cpp/utility/as const") (C++17) | obtains a reference to const to its argument (function template) | | [declval](../utility/declval "cpp/utility/declval") (C++11) | obtains a reference to its argument for use in unevaluated context (function template) | | [to\_underlying](../utility/to_underlying "cpp/utility/to underlying") (C++23) | converts an enumeration to its underlying type (function template) | | [cmp\_equalcmp\_not\_equalcmp\_lesscmp\_greatercmp\_less\_equalcmp\_greater\_equal](../utility/intcmp "cpp/utility/intcmp") (C++20) | compares two integer values without value change caused by conversion (function template) | | [in\_range](../utility/in_range "cpp/utility/in range") (C++20) | checks if an integer value is in the range of a given integer type (function template) | | [unreachable](../utility/unreachable "cpp/utility/unreachable") (C++23) | marks unreachable point of execution (function) | | [make\_pair](../utility/pair/make_pair "cpp/utility/pair/make pair") | creates a `pair` object of type, defined by the argument types (function template) | | [operator==operator!=operator<operator<=operator>operator>=operator<=>](../utility/pair/operator_cmp "cpp/utility/pair/operator cmp") (removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(C++20) | lexicographically compares the values in the pair (function template) | | [std::swap(std::pair)](../utility/pair/swap2 "cpp/utility/pair/swap2") (C++11) | specializes the `[std::swap](../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | | [std::get(std::pair)](../utility/pair/get "cpp/utility/pair/get") (C++11) | accesses an element of a `pair` (function template) | | Classes | | [pair](../utility/pair "cpp/utility/pair") | implements binary tuple, i.e. a pair of values (class template) | | [tuple\_size](../utility/tuple_size "cpp/utility/tuple size") (C++11) | obtains the number of elements of a tuple-like type (class template) | | [tuple\_element](../utility/tuple_element "cpp/utility/tuple element") (C++11) | obtains the element types of a tuple-like type (class template) | | [std::tuple\_size<std::pair>](../utility/pair/tuple_size "cpp/utility/pair/tuple size") (C++11) | obtains the size of a `pair` (class template specialization) | | [std::tuple\_element<std::pair>](../utility/pair/tuple_element "cpp/utility/pair/tuple element") (C++11) | obtains the type of the elements of `pair` (class template specialization) | | [integer\_sequence](../utility/integer_sequence "cpp/utility/integer sequence") (C++14) | implements compile-time sequence of integers (class template) | | Forward declarations | | Defined in header `[<tuple>](tuple "cpp/header/tuple")` | | [tuple](../utility/tuple "cpp/utility/tuple") (C++11) | implements fixed size container, which holds elements of possibly different types (class template) | | Helpers | | [piecewise\_construct\_t](../utility/piecewise_construct_t "cpp/utility/piecewise construct t") (C++11) | tag type used to select correct function overload for piecewise construction (class) | | [piecewise\_construct](../utility/piecewise_construct "cpp/utility/piecewise construct") (C++11) | an object of type `piecewise_construct_t` used to disambiguate functions for piecewise construction (constant) | | [in\_place in\_place\_type in\_place\_index in\_place\_t in\_place\_type\_t in\_place\_index\_t](../utility/in_place "cpp/utility/in place") (C++17) | in-place construction tag (class template) | ### Synopsis ``` #include <compare> #include <initializer_list> namespace std { // swap template<class T> constexpr void swap(T& a, T& b) noexcept(/* see description */); template<class T, size_t N> constexpr void swap(T (&a)[N], T (&b)[N]) noexcept(is_nothrow_swappable_v<T>); // exchange template<class T, class U = T> constexpr T exchange(T& obj, U&& new_val); // forward/move template<class T> constexpr T&& forward(remove_reference_t<T>& t) noexcept; template<class T> constexpr T&& forward(remove_reference_t<T>&& t) noexcept; template<class T, class U> constexpr /* see description */ forward_like(U&& x) noexcept; template<class T> constexpr remove_reference_t<T>&& move(T&&) noexcept; template<class T> constexpr conditional_t< !is_nothrow_move_constructible_v<T> && is_copy_constructible_v<T>, const T&, T&&> move_if_noexcept(T& x) noexcept; // as_const template<class T> constexpr add_const_t<T>& as_const(T& t) noexcept; template<class T> void as_const(const T&&) = delete; // declval template<class T> add_rvalue_reference_t<T> declval() noexcept; // as unevaluated operand // integer comparison functions template<class T, class U> constexpr bool cmp_equal(T t, U u) noexcept; template<class T, class U> constexpr bool cmp_not_equal(T t, U u) noexcept; template<class T, class U> constexpr bool cmp_less(T t, U u) noexcept; template<class T, class U> constexpr bool cmp_greater(T t, U u) noexcept; template<class T, class U> constexpr bool cmp_less_equal(T t, U u) noexcept; template<class T, class U> constexpr bool cmp_greater_equal(T t, U u) noexcept; template<class R, class T> constexpr bool in_range(T t) noexcept; // to_underlying template<class T> constexpr underlying_type_t<T> to_underlying(T value) noexcept; // compile-time integer sequences template<class T, T...> struct integer_sequence; template<size_t... I> using index_sequence = integer_sequence<size_t, I...>; template<class T, T N> using make_integer_sequence = integer_sequence<T, /* see description */>; template<size_t N> using make_index_sequence = make_integer_sequence<size_t, N>; template<class... T> using index_sequence_for = make_index_sequence<sizeof...(T)>; // class template pair template<class T1, class T2> struct pair; // pair specialized algorithms template<class T1, class T2> constexpr bool operator==(const pair<T1, T2>&, const pair<T1, T2>&); template<class T1, class T2> constexpr common_comparison_category_t</*synth-three-way-result*/<T1>, /*synth-three-way-result*/<T2>> operator<=>(const pair<T1, T2>&, const pair<T1, T2>&); template<class T1, class T2> constexpr void swap(pair<T1, T2>& x, pair<T1, T2>& y) noexcept(noexcept(x.swap(y))); template<class T1, class T2> constexpr /* see description */ make_pair(T1&&, T2&&); // tuple-like access to pair template<class T> struct tuple_size; template<size_t I, class T> struct tuple_element; template<class T1, class T2> struct tuple_size<pair<T1, T2>>; template<size_t I, class T1, class T2> struct tuple_element<I, pair<T1, T2>>; template<size_t I, class T1, class T2> constexpr tuple_element_t<I, pair<T1, T2>>& get(pair<T1, T2>&) noexcept; template<size_t I, class T1, class T2> constexpr tuple_element_t<I, pair<T1, T2>>&& get(pair<T1, T2>&&) noexcept; template<size_t I, class T1, class T2> constexpr const tuple_element_t<I, pair<T1, T2>>& get(const pair<T1, T2>&) noexcept; template<size_t I, class T1, class T2> constexpr const tuple_element_t<I, pair<T1, T2>>&& get(const pair<T1, T2>&&) noexcept; template<class T1, class T2> constexpr T1& get(pair<T1, T2>& p) noexcept; template<class T1, class T2> constexpr const T1& get(const pair<T1, T2>& p) noexcept; template<class T1, class T2> constexpr T1&& get(pair<T1, T2>&& p) noexcept; template<class T1, class T2> constexpr const T1&& get(const pair<T1, T2>&& p) noexcept; template<class T2, class T1> constexpr T2& get(pair<T1, T2>& p) noexcept; template<class T2, class T1> constexpr const T2& get(const pair<T1, T2>& p) noexcept; template<class T2, class T1> constexpr T2&& get(pair<T1, T2>&& p) noexcept; template<class T2, class T1> constexpr const T2&& get(const pair<T1, T2>&& p) noexcept; // pair piecewise construction struct piecewise_construct_t { explicit piecewise_construct_t() = default; }; inline constexpr piecewise_construct_t piecewise_construct{}; template<class... Types> class tuple; // defined in <tuple> // in-place construction struct in_place_t { explicit in_place_t() = default; }; inline constexpr in_place_t in_place{}; template<class T> struct in_place_type_t { explicit in_place_type_t() = default; }; template<class T> inline constexpr in_place_type_t<T> in_place_type{}; template<size_t I> struct in_place_index_t { explicit in_place_index_t() = default; }; template<size_t I> inline constexpr in_place_index_t<I> in_place_index{}; // unreachable [[noreturn]] void unreachable(); } // deprecated namespace std::rel_ops { template<class T> bool operator!=(const T&, const T&); template<class T> bool operator> (const T&, const T&); template<class T> bool operator<=(const T&, const T&); template<class T> bool operator>=(const T&, const T&); } ``` #### Class template `[std::integer\_sequence](../utility/integer_sequence "cpp/utility/integer sequence")` ``` namespace std { template<class T, T... I> struct integer_sequence { using value_type = T; static constexpr size_t size() noexcept { return sizeof...(I); } }; } ``` #### Class template `[std::pair](../utility/pair "cpp/utility/pair")` ``` namespace std { template<class T1, class T2> struct pair { using first_type = T1; using second_type = T2; T1 first; T2 second; pair(const pair&) = default; pair(pair&&) = default; constexpr explicit(/* see description */) pair(); constexpr explicit(/* see description */) pair(const T1& x, const T2& y); template<class U1 = T1, class U2 = T2> constexpr explicit(/* see description */) pair(U1&& x, U2&& y); template<class U1, class U2> constexpr explicit(/* see description */) pair(const pair<U1, U2>& p); template<class U1, class U2> constexpr explicit(/* see description */) pair(pair<U1, U2>&& p); template<class... Args1, class... Args2> constexpr pair(piecewise_construct_t, tuple<Args1...> first_args, tuple<Args2...> second_args); constexpr pair& operator=(const pair& p); template<class U1, class U2> constexpr pair& operator=(const pair<U1, U2>& p); constexpr pair& operator=(pair&& p) noexcept(/* see description */); template<class U1, class U2> constexpr pair& operator=(pair<U1, U2>&& p); constexpr void swap(pair& p) noexcept(/* see description */); }; template<class T1, class T2> pair(T1, T2) -> pair<T1, T2>; } ``` ### See also | | | | --- | --- | | [<tuple>](tuple "cpp/header/tuple") (C++11) | `[std::tuple](../utility/tuple "cpp/utility/tuple")` class template | cpp Standard library header <istream> Standard library header <istream> ================================= This header is part of the [input/output](../io "cpp/io") library. | | | --- | | Classes | | [basic\_istream](../io/basic_istream "cpp/io/basic istream") | wraps a given abstract device (`[std::basic\_streambuf](../io/basic_streambuf "cpp/io/basic streambuf")`) and provides high-level input interface (class template) | | `[std::istream](../io/basic_istream "cpp/io/basic istream")` | `[std::basic\_istream](http://en.cppreference.com/w/cpp/io/basic_istream)<char>` (typedef) | | `[std::wistream](../io/basic_istream "cpp/io/basic istream")` | `[std::basic\_istream](http://en.cppreference.com/w/cpp/io/basic_istream)<wchar\_t>` (typedef) | | [basic\_iostream](../io/basic_iostream "cpp/io/basic iostream") | wraps a given abstract device (`[std::basic\_streambuf](../io/basic_streambuf "cpp/io/basic streambuf")`) and provides high-level input/output interface (class template) | | `[std::iostream](../io/basic_iostream "cpp/io/basic iostream")` | `[std::basic\_iostream](http://en.cppreference.com/w/cpp/io/basic_iostream)<char>` (typedef) | | `[std::wiostream](../io/basic_iostream "cpp/io/basic iostream")` | `[std::basic\_iostream](http://en.cppreference.com/w/cpp/io/basic_iostream)<wchar\_t>` (typedef) | | Functions | | [operator>>(std::basic\_istream)](../io/basic_istream/operator_gtgt2 "cpp/io/basic istream/operator gtgt2") | extracts characters and character arrays (function template) | | Manipulators | | [ws](../io/manip/ws "cpp/io/manip/ws") | consumes whitespace (function template) | ### Synopsis ``` namespace std { template<class CharT, class Traits = char_traits<CharT>> class basic_istream; using istream = basic_istream<char>; using wistream = basic_istream<wchar_t>; template<class CharT, class Traits = char_traits<CharT>> class basic_iostream; using iostream = basic_iostream<char>; using wiostream = basic_iostream<wchar_t>; template<class CharT, class Traits> basic_istream<CharT, Traits>& ws(basic_istream<CharT, Traits>& is); template<class Istream, class T> Istream&& operator>>(Istream&& is, T&& x); } ``` #### Class template `[std::basic\_istream](../io/basic_istream "cpp/io/basic istream")` ``` namespace std { template<class CharT, class Traits = char_traits<CharT>> class basic_istream : virtual public basic_ios<CharT, Traits> { public: // types (inherited from basic_ios) using char_type = CharT; using int_type = typename Traits::int_type; using pos_type = typename Traits::pos_type; using off_type = typename Traits::off_type; using traits_type = Traits; // constructor/destructor explicit basic_istream(basic_streambuf<CharT, Traits>* sb); virtual ~basic_istream(); // prefix/suffix class sentry; // formatted input basic_istream<CharT, Traits>& operator>>(basic_istream<CharT, Traits>& (*pf)(basic_istream<CharT, Traits>&)); basic_istream<CharT, Traits>& operator>>(basic_ios<CharT, Traits>& (*pf)(basic_ios<CharT, Traits>&)); basic_istream<CharT, Traits>& operator>>(ios_base& (*pf)(ios_base&)); basic_istream<CharT, Traits>& operator>>(bool& n); basic_istream<CharT, Traits>& operator>>(short& n); basic_istream<CharT, Traits>& operator>>(unsigned short& n); basic_istream<CharT, Traits>& operator>>(int& n); basic_istream<CharT, Traits>& operator>>(unsigned int& n); basic_istream<CharT, Traits>& operator>>(long& n); basic_istream<CharT, Traits>& operator>>(unsigned long& n); basic_istream<CharT, Traits>& operator>>(long long& n); basic_istream<CharT, Traits>& operator>>(unsigned long long& n); basic_istream<CharT, Traits>& operator>>(float& f); basic_istream<CharT, Traits>& operator>>(double& f); basic_istream<CharT, Traits>& operator>>(long double& f); basic_istream<CharT, Traits>& operator>>(void*& p); basic_istream<CharT, Traits>& operator>>(basic_streambuf<char_type, Traits>* sb); // unformatted input streamsize gcount() const; int_type get(); basic_istream<CharT, Traits>& get(char_type& c); basic_istream<CharT, Traits>& get(char_type* s, streamsize n); basic_istream<CharT, Traits>& get(char_type* s, streamsize n, char_type delim); basic_istream<CharT, Traits>& get(basic_streambuf<char_type, Traits>& sb); basic_istream<CharT, Traits>& get(basic_streambuf<char_type, Traits>& sb, char_type delim); basic_istream<CharT, Traits>& getline(char_type* s, streamsize n); basic_istream<CharT, Traits>& getline(char_type* s, streamsize n, char_type delim); basic_istream<CharT, Traits>& ignore(streamsize n = 1, int_type delim = Traits::eof()); int_type peek(); basic_istream<CharT, Traits>& read (char_type* s, streamsize n); streamsize readsome(char_type* s, streamsize n); basic_istream<CharT, Traits>& putback(char_type c); basic_istream<CharT, Traits>& unget(); int sync(); pos_type tellg(); basic_istream<CharT, Traits>& seekg(pos_type); basic_istream<CharT, Traits>& seekg(off_type, ios_base::seekdir); protected: // copy/move constructor basic_istream(const basic_istream&) = delete; basic_istream(basic_istream&& rhs); // assign and swap basic_istream& operator=(const basic_istream&) = delete; basic_istream& operator=(basic_istream&& rhs); void swap(basic_istream& rhs); }; // character extraction templates template<class CharT, class Traits> basic_istream<CharT, Traits>& operator>>(basic_istream<CharT, Traits>&, CharT&); template<class Traits> basic_istream<char, Traits>& operator>>(basic_istream<char, Traits>&, unsigned char&); template<class Traits> basic_istream<char, Traits>& operator>>(basic_istream<char, Traits>&, signed char&); template<class CharT, class Traits, size_t N> basic_istream<CharT, Traits>& operator>>(basic_istream<CharT, Traits>&, CharT(&)[N]); template<class Traits, size_t N> basic_istream<char, Traits>& operator>>(basic_istream<char, Traits>&, unsigned char(&)[N]); template<class Traits, size_t N> basic_istream<char, Traits>& operator>>(basic_istream<char, Traits>&, signed char(&)[N]); } ``` #### Class `[std::basic\_istream::sentry](../io/basic_istream/sentry "cpp/io/basic istream/sentry")` ``` namespace std { template<class CharT, class Traits = char_traits<CharT>> class basic_istream<CharT, Traits>::sentry { bool ok_; // exposition only public: explicit sentry(basic_istream<CharT, Traits>& is, bool noskipws = false); ~sentry(); explicit operator bool() const { return ok_; } sentry(const sentry&) = delete; sentry& operator=(const sentry&) = delete; }; } ``` #### Class template `[std::basic\_iostream](../io/basic_iostream "cpp/io/basic iostream")` ``` namespace std { template<class CharT, class Traits = char_traits<CharT>> class basic_iostream : public basic_istream<CharT, Traits>, public basic_ostream<CharT, Traits> { public: using char_type = CharT; using int_type = typename Traits::int_type; using pos_type = typename Traits::pos_type; using off_type = typename Traits::off_type; using traits_type = Traits; // constructor explicit basic_iostream(basic_streambuf<CharT, Traits>* sb); // destructor virtual ~basic_iostream(); protected: // constructor basic_iostream(const basic_iostream&) = delete; basic_iostream(basic_iostream&& rhs); // assign and swap basic_iostream& operator=(const basic_iostream&) = delete; basic_iostream& operator=(basic_iostream&& rhs); void swap(basic_iostream& rhs); }; } ```
programming_docs
cpp Standard library header <valarray> Standard library header <valarray> ================================== This header is part of the [numeric](../numeric "cpp/numeric") library. | | | --- | | Includes | | [<initializer\_list>](initializer_list "cpp/header/initializer list") (C++11) | `[std::initializer\_list](../utility/initializer_list "cpp/utility/initializer list")` class template | | Classes | | [valarray](../numeric/valarray "cpp/numeric/valarray") | Numeric arrays and array slices (class template) | | [slice](../numeric/valarray/slice "cpp/numeric/valarray/slice") | BLAS-like slice of a valarray: starting index, length, stride (class) | | [slice\_array](../numeric/valarray/slice_array "cpp/numeric/valarray/slice array") | proxy to a subset of a valarray after applying a slice (class template) | | [gslice](../numeric/valarray/gslice "cpp/numeric/valarray/gslice") | generalized slice of a valarray: starting index, set of lengths, set of strides (class) | | [gslice\_array](../numeric/valarray/gslice_array "cpp/numeric/valarray/gslice array") | proxy to a subset of a valarray after applying a gslice (class template) | | [mask\_array](../numeric/valarray/mask_array "cpp/numeric/valarray/mask array") | proxy to a subset of a valarray after applying a boolean mask `operator[]` (class template) | | [indirect\_array](../numeric/valarray/indirect_array "cpp/numeric/valarray/indirect array") | proxy to a subset of a valarray after applying indirect `operator[]` (class template) | | Functions | | Operations | | [std::swap(std::valarray)](../numeric/valarray/swap2 "cpp/numeric/valarray/swap2") (C++11) | specializes the `[std::swap](../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | | [std::begin(std::valarray)](../numeric/valarray/begin2 "cpp/numeric/valarray/begin2") (C++11) | overloads `[std::begin](../iterator/begin "cpp/iterator/begin")` (function template) | | [std::end(std::valarray)](../numeric/valarray/end2 "cpp/numeric/valarray/end2") (C++11) | specializes `[std::end](../iterator/end "cpp/iterator/end")` (function template) | | [operator+operator-operator\*operator/operator%operator&operator|operator^operator<<operator>>operator&&operator||](../numeric/valarray/operator_arith3 "cpp/numeric/valarray/operator arith3") | applies binary operators to each element of two valarrays, or a valarray and a value (function template) | | [operator==operator!=operator<operator<=operator>operator>=](../numeric/valarray/operator_cmp "cpp/numeric/valarray/operator cmp") | compares two valarrays or a valarray with a value (function template) | | [abs(std::valarray)](../numeric/valarray/abs "cpp/numeric/valarray/abs") | applies the function `abs` to each element of valarray (function template) | | Exponential functions | | [exp(std::valarray)](../numeric/valarray/exp "cpp/numeric/valarray/exp") | applies the function `[std::exp](../numeric/math/exp "cpp/numeric/math/exp")` to each element of valarray (function template) | | [log(std::valarray)](../numeric/valarray/log "cpp/numeric/valarray/log") | applies the function `[std::log](../numeric/math/log "cpp/numeric/math/log")` to each element of valarray (function template) | | [log10(std::valarray)](../numeric/valarray/log10 "cpp/numeric/valarray/log10") | applies the function `[std::log10](../numeric/math/log10 "cpp/numeric/math/log10")` to each element of valarray (function template) | | Power functions | | [pow(std::valarray)](../numeric/valarray/pow "cpp/numeric/valarray/pow") | applies the function `[std::pow](../numeric/math/pow "cpp/numeric/math/pow")` to two valarrays or a valarray and a value (function template) | | [sqrt(std::valarray)](../numeric/valarray/sqrt "cpp/numeric/valarray/sqrt") | applies the function `[std::sqrt](../numeric/math/sqrt "cpp/numeric/math/sqrt")` to each element of valarray (function template) | | Trigonometric functions | | [sin(std::valarray)](../numeric/valarray/sin "cpp/numeric/valarray/sin") | applies the function `[std::sin](../numeric/math/sin "cpp/numeric/math/sin")` to each element of valarray (function template) | | [cos(std::valarray)](../numeric/valarray/cos "cpp/numeric/valarray/cos") | applies the function `[std::cos](../numeric/math/cos "cpp/numeric/math/cos")` to each element of valarray (function template) | | [tan(std::valarray)](../numeric/valarray/tan "cpp/numeric/valarray/tan") | applies the function `[std::tan](../numeric/math/tan "cpp/numeric/math/tan")` to each element of valarray (function template) | | [asin(std::valarray)](../numeric/valarray/asin "cpp/numeric/valarray/asin") | applies the function `[std::asin](../numeric/math/asin "cpp/numeric/math/asin")` to each element of valarray (function template) | | [acos(std::valarray)](../numeric/valarray/acos "cpp/numeric/valarray/acos") | applies the function `[std::acos](../numeric/math/acos "cpp/numeric/math/acos")` to each element of valarray (function template) | | [atan(std::valarray)](../numeric/valarray/atan "cpp/numeric/valarray/atan") | applies the function `[std::atan](../numeric/math/atan "cpp/numeric/math/atan")` to each element of valarray (function template) | | [atan2(std::valarray)](../numeric/valarray/atan2 "cpp/numeric/valarray/atan2") | applies the function `[std::atan2](../numeric/math/atan2 "cpp/numeric/math/atan2")` to a valarray and a value (function template) | | Hyperbolic functions | | [sinh(std::valarray)](../numeric/valarray/sinh "cpp/numeric/valarray/sinh") | applies the function `[std::sinh](../numeric/math/sinh "cpp/numeric/math/sinh")` to each element of valarray (function template) | | [cosh(std::valarray)](../numeric/valarray/cosh "cpp/numeric/valarray/cosh") | applies the function `[std::cosh](../numeric/math/cosh "cpp/numeric/math/cosh")` to each element of valarray (function template) | | [tanh(std::valarray)](../numeric/valarray/tanh "cpp/numeric/valarray/tanh") | applies the function `[std::tanh](../numeric/math/tanh "cpp/numeric/math/tanh")` to each element of valarray (function template) | ### Synopsis ``` #include <initializer_list> namespace std { template<class T> class valarray; // An array of type T class slice; // a BLAS-like slice out of an array template<class T> class slice_array; class gslice; // a generalized slice out of an array template<class T> class gslice_array; template<class T> class mask_array; // a masked array template<class T> class indirect_array; // an indirected array template<class T> void swap(valarray<T>&, valarray<T>&) noexcept; template<class T> valarray<T> operator* (const valarray<T>&, const valarray<T>&); template<class T> valarray<T> operator* (const valarray<T>&, const typename valarray<T>::value_type&); template<class T> valarray<T> operator* (const typename valarray<T>::value_type&, const valarray<T>&); template<class T> valarray<T> operator/ (const valarray<T>&, const valarray<T>&); template<class T> valarray<T> operator/ (const valarray<T>&, const typename valarray<T>::value_type&); template<class T> valarray<T> operator/ (const typename valarray<T>::value_type&, const valarray<T>&); template<class T> valarray<T> operator% (const valarray<T>&, const valarray<T>&); template<class T> valarray<T> operator% (const valarray<T>&, const typename valarray<T>::value_type&); template<class T> valarray<T> operator% (const typename valarray<T>::value_type&, const valarray<T>&); template<class T> valarray<T> operator+ (const valarray<T>&, const valarray<T>&); template<class T> valarray<T> operator+ (const valarray<T>&, const typename valarray<T>::value_type&); template<class T> valarray<T> operator+ (const typename valarray<T>::value_type&, const valarray<T>&); template<class T> valarray<T> operator- (const valarray<T>&, const valarray<T>&); template<class T> valarray<T> operator- (const valarray<T>&, const typename valarray<T>::value_type&); template<class T> valarray<T> operator- (const typename valarray<T>::value_type&, const valarray<T>&); template<class T> valarray<T> operator^ (const valarray<T>&, const valarray<T>&); template<class T> valarray<T> operator^ (const valarray<T>&, const typename valarray<T>::value_type&); template<class T> valarray<T> operator^ (const typename valarray<T>::value_type&, const valarray<T>&); template<class T> valarray<T> operator& (const valarray<T>&, const valarray<T>&); template<class T> valarray<T> operator& (const valarray<T>&, const typename valarray<T>::value_type&); template<class T> valarray<T> operator& (const typename valarray<T>::value_type&, const valarray<T>&); template<class T> valarray<T> operator| (const valarray<T>&, const valarray<T>&); template<class T> valarray<T> operator| (const valarray<T>&, const typename valarray<T>::value_type&); template<class T> valarray<T> operator| (const typename valarray<T>::value_type&, const valarray<T>&); template<class T> valarray<T> operator<<(const valarray<T>&, const valarray<T>&); template<class T> valarray<T> operator<<(const valarray<T>&, const typename valarray<T>::value_type&); template<class T> valarray<T> operator<<(const typename valarray<T>::value_type&, const valarray<T>&); template<class T> valarray<T> operator>>(const valarray<T>&, const valarray<T>&); template<class T> valarray<T> operator>>(const valarray<T>&, const typename valarray<T>::value_type&); template<class T> valarray<T> operator>>(const typename valarray<T>::value_type&, const valarray<T>&); template<class T> valarray<bool> operator&&(const valarray<T>&, const valarray<T>&); template<class T> valarray<bool> operator&&(const valarray<T>&, const typename valarray<T>::value_type&); template<class T> valarray<bool> operator&&(const typename valarray<T>::value_type&, const valarray<T>&); template<class T> valarray<bool> operator||(const valarray<T>&, const valarray<T>&); template<class T> valarray<bool> operator||(const valarray<T>&, const typename valarray<T>::value_type&); template<class T> valarray<bool> operator||(const typename valarray<T>::value_type&, const valarray<T>&); template<class T> valarray<bool> operator==(const valarray<T>&, const valarray<T>&); template<class T> valarray<bool> operator==(const valarray<T>&, const typename valarray<T>::value_type&); template<class T> valarray<bool> operator==(const typename valarray<T>::value_type&, const valarray<T>&); template<class T> valarray<bool> operator!=(const valarray<T>&, const valarray<T>&); template<class T> valarray<bool> operator!=(const valarray<T>&, const typename valarray<T>::value_type&); template<class T> valarray<bool> operator!=(const typename valarray<T>::value_type&, const valarray<T>&); template<class T> valarray<bool> operator< (const valarray<T>&, const valarray<T>&); template<class T> valarray<bool> operator< (const valarray<T>&, const typename valarray<T>::value_type&); template<class T> valarray<bool> operator< (const typename valarray<T>::value_type&, const valarray<T>&); template<class T> valarray<bool> operator> (const valarray<T>&, const valarray<T>&); template<class T> valarray<bool> operator> (const valarray<T>&, const typename valarray<T>::value_type&); template<class T> valarray<bool> operator> (const typename valarray<T>::value_type&, const valarray<T>&); template<class T> valarray<bool> operator<=(const valarray<T>&, const valarray<T>&); template<class T> valarray<bool> operator<=(const valarray<T>&, const typename valarray<T>::value_type&); template<class T> valarray<bool> operator<=(const typename valarray<T>::value_type&, const valarray<T>&); template<class T> valarray<bool> operator>=(const valarray<T>&, const valarray<T>&); template<class T> valarray<bool> operator>=(const valarray<T>&, const typename valarray<T>::value_type&); template<class T> valarray<bool> operator>=(const typename valarray<T>::value_type&, const valarray<T>&); template<class T> valarray<T> abs (const valarray<T>&); template<class T> valarray<T> acos (const valarray<T>&); template<class T> valarray<T> asin (const valarray<T>&); template<class T> valarray<T> atan (const valarray<T>&); template<class T> valarray<T> atan2(const valarray<T>&, const valarray<T>&); template<class T> valarray<T> atan2(const valarray<T>&, const typename valarray<T>::value_type&); template<class T> valarray<T> atan2(const typename valarray<T>::value_type&, const valarray<T>&); template<class T> valarray<T> cos (const valarray<T>&); template<class T> valarray<T> cosh (const valarray<T>&); template<class T> valarray<T> exp (const valarray<T>&); template<class T> valarray<T> log (const valarray<T>&); template<class T> valarray<T> log10(const valarray<T>&); template<class T> valarray<T> pow(const valarray<T>&, const valarray<T>&); template<class T> valarray<T> pow(const valarray<T>&, const typename valarray<T>::value_type&); template<class T> valarray<T> pow(const typename valarray<T>::value_type&, const valarray<T>&); template<class T> valarray<T> sin (const valarray<T>&); template<class T> valarray<T> sinh (const valarray<T>&); template<class T> valarray<T> sqrt (const valarray<T>&); template<class T> valarray<T> tan (const valarray<T>&); template<class T> valarray<T> tanh (const valarray<T>&); template<class T> /* unspecified1 */ begin(valarray<T>& v); template<class T> /* unspecified2 */ begin(const valarray<T>& v); template<class T> /* unspecified1 */ end(valarray<T>& v); template<class T> /* unspecified2 */ end(const valarray<T>& v); } ``` ### Class template `[std::valarray](../numeric/valarray "cpp/numeric/valarray")` ``` namespace std { template<class T> class valarray { public: using value_type = T; // construct/destroy valarray(); explicit valarray(size_t); valarray(const T&, size_t); valarray(const T*, size_t); valarray(const valarray&); valarray(valarray&&) noexcept; valarray(const slice_array<T>&); valarray(const gslice_array<T>&); valarray(const mask_array<T>&); valarray(const indirect_array<T>&); valarray(initializer_list<T>); ~valarray(); // assignment valarray& operator=(const valarray&); valarray& operator=(valarray&&) noexcept; valarray& operator=(initializer_list<T>); valarray& operator=(const T&); valarray& operator=(const slice_array<T>&); valarray& operator=(const gslice_array<T>&); valarray& operator=(const mask_array<T>&); valarray& operator=(const indirect_array<T>&); // element access const T& operator[](size_t) const; T& operator[](size_t); // subset operations valarray operator[](slice) const; slice_array<T> operator[](slice); valarray operator[](const gslice&) const; gslice_array<T> operator[](const gslice&); valarray operator[](const valarray<bool>&) const; mask_array<T> operator[](const valarray<bool>&); valarray operator[](const valarray<size_t>&) const; indirect_array<T> operator[](const valarray<size_t>&); // unary operators valarray operator+() const; valarray operator-() const; valarray operator~() const; valarray<bool> operator!() const; // compound assignment valarray& operator*= (const T&); valarray& operator/= (const T&); valarray& operator%= (const T&); valarray& operator+= (const T&); valarray& operator-= (const T&); valarray& operator^= (const T&); valarray& operator&= (const T&); valarray& operator|= (const T&); valarray& operator<<=(const T&); valarray& operator>>=(const T&); valarray& operator*= (const valarray&); valarray& operator/= (const valarray&); valarray& operator%= (const valarray&); valarray& operator+= (const valarray&); valarray& operator-= (const valarray&); valarray& operator^= (const valarray&); valarray& operator|= (const valarray&); valarray& operator&= (const valarray&); valarray& operator<<=(const valarray&); valarray& operator>>=(const valarray&); // member functions void swap(valarray&) noexcept; size_t size() const; T sum() const; T min() const; T max() const; valarray shift (int) const; valarray cshift(int) const; valarray apply(T func(T)) const; valarray apply(T func(const T&)) const; void resize(size_t sz, T c = T()); }; template<class T, size_t cnt> valarray(const T(&)[cnt], size_t) -> valarray<T>; } ``` ### Class `[std::slice](../numeric/valarray/slice "cpp/numeric/valarray/slice")` ``` namespace std { class slice { public: slice(); slice(size_t, size_t, size_t); size_t start() const; size_t size() const; size_t stride() const; friend bool operator==(const slice& x, const slice& y); }; } ``` ### Class template `[std::slice\_array](../numeric/valarray/slice_array "cpp/numeric/valarray/slice array")` ``` namespace std { template<class T> class slice_array { public: using value_type = T; void operator= (const valarray<T>&) const; void operator*= (const valarray<T>&) const; void operator/= (const valarray<T>&) const; void operator%= (const valarray<T>&) const; void operator+= (const valarray<T>&) const; void operator-= (const valarray<T>&) const; void operator^= (const valarray<T>&) const; void operator&= (const valarray<T>&) const; void operator|= (const valarray<T>&) const; void operator<<=(const valarray<T>&) const; void operator>>=(const valarray<T>&) const; slice_array(const slice_array&); ~slice_array(); const slice_array& operator=(const slice_array&) const; void operator=(const T&) const; slice_array() = delete; // as implied by declaring copy constructor above }; } ``` ### Class `[std::gslice](../numeric/valarray/gslice "cpp/numeric/valarray/gslice")` ``` namespace std { class gslice { public: gslice(); gslice(size_t s, const valarray<size_t>& l, const valarray<size_t>& d); size_t start() const; valarray<size_t> size() const; valarray<size_t> stride() const; }; } ``` ### Class template `[std::gslice\_array](../numeric/valarray/gslice_array "cpp/numeric/valarray/gslice array")` ``` namespace std { template<class T> class gslice_array { public: using value_type = T; void operator= (const valarray<T>&) const; void operator*= (const valarray<T>&) const; void operator/= (const valarray<T>&) const; void operator%= (const valarray<T>&) const; void operator+= (const valarray<T>&) const; void operator-= (const valarray<T>&) const; void operator^= (const valarray<T>&) const; void operator&= (const valarray<T>&) const; void operator|= (const valarray<T>&) const; void operator<<=(const valarray<T>&) const; void operator>>=(const valarray<T>&) const; gslice_array(const gslice_array&); ~gslice_array(); const gslice_array& operator=(const gslice_array&) const; void operator=(const T&) const; gslice_array() = delete; // as implied by declaring copy constructor above }; } ``` ### Class template `[std::mask\_array](../numeric/valarray/mask_array "cpp/numeric/valarray/mask array")` ``` namespace std { template<class T> class mask_array { public: using value_type = T; void operator= (const valarray<T>&) const; void operator*= (const valarray<T>&) const; void operator/= (const valarray<T>&) const; void operator%= (const valarray<T>&) const; void operator+= (const valarray<T>&) const; void operator-= (const valarray<T>&) const; void operator^= (const valarray<T>&) const; void operator&= (const valarray<T>&) const; void operator|= (const valarray<T>&) const; void operator<<=(const valarray<T>&) const; void operator>>=(const valarray<T>&) const; mask_array(const mask_array&); ~mask_array(); const mask_array& operator=(const mask_array&) const; void operator=(const T&) const; mask_array() = delete; // as implied by declaring copy constructor above }; } ``` ### Class template `[std::indirect\_array](../numeric/valarray/indirect_array "cpp/numeric/valarray/indirect array")` ``` namespace std { template<class T> class indirect_array { public: using value_type = T; void operator= (const valarray<T>&) const; void operator*= (const valarray<T>&) const; void operator/= (const valarray<T>&) const; void operator%= (const valarray<T>&) const; void operator+= (const valarray<T>&) const; void operator-= (const valarray<T>&) const; void operator^= (const valarray<T>&) const; void operator&= (const valarray<T>&) const; void operator|= (const valarray<T>&) const; void operator<<=(const valarray<T>&) const; void operator>>=(const valarray<T>&) const; indirect_array(const indirect_array&); ~indirect_array(); const indirect_array& operator=(const indirect_array&) const; void operator=(const T&) const; indirect_array() = delete; // as implied by declaring copy constructor above }; } ```
programming_docs
cpp Standard library header <cwchar> Standard library header <cwchar> ================================ This header was originally in the C standard library as `<wchar.h>`. This header is part of the null-terminated [wide](../string/wide "cpp/string/wide") and [multibyte](../string/multibyte "cpp/string/multibyte") strings libraries. It also provides some [C-style I/O](../io/c "cpp/io/c") functions and conversion from [C-style Date](../chrono/c "cpp/chrono/c"). ### Macros | | | | --- | --- | | [NULL](../types/null "cpp/types/NULL") | implementation-defined null pointer constant (macro constant) | | WEOF | a non-character value of type wint\_t used to indicate errors (macro constant) | | WCHAR\_MIN | the smallest valid value of wchar\_t (macro constant) | | WCHAR\_MAX | the largest valid value of wchar\_t (macro constant) | ### Types | | | | --- | --- | | [mbstate\_t](../string/multibyte/mbstate_t "cpp/string/multibyte/mbstate t") | conversion state information necessary to iterate multibyte character strings (class) | | [size\_t](../types/size_t "cpp/types/size t") | unsigned integer type returned by the [`sizeof`](../language/sizeof "cpp/language/sizeof") operator (typedef) | | `wint_t` | integer type that can hold any valid wide character and at least one more value | | [tm](../chrono/c/tm "cpp/chrono/c/tm") | calendar time type (class) | ### Functions | | | --- | | String manipulation | | [wcscpy](../string/wide/wcscpy "cpp/string/wide/wcscpy") | copies one wide string to another (function) | | [wcsncpy](../string/wide/wcsncpy "cpp/string/wide/wcsncpy") | copies a certain amount of wide characters from one string to another (function) | | [wcscat](../string/wide/wcscat "cpp/string/wide/wcscat") | appends a copy of one wide string to another (function) | | [wcsncat](../string/wide/wcsncat "cpp/string/wide/wcsncat") | appends a certain amount of wide characters from one wide string to another (function) | | [wcsxfrm](../string/wide/wcsxfrm "cpp/string/wide/wcsxfrm") | transform a wide string so that wcscmp would produce the same result as wcscoll (function) | | String examination | | [wcslen](../string/wide/wcslen "cpp/string/wide/wcslen") | returns the length of a wide string (function) | | [wcscmp](../string/wide/wcscmp "cpp/string/wide/wcscmp") | compares two wide strings (function) | | [wcsncmp](../string/wide/wcsncmp "cpp/string/wide/wcsncmp") | compares a certain amount of characters from two wide strings (function) | | [wcscoll](../string/wide/wcscoll "cpp/string/wide/wcscoll") | compares two wide strings in accordance to the current locale (function) | | [wcschr](../string/wide/wcschr "cpp/string/wide/wcschr") | finds the first occurrence of a wide character in a wide string (function) | | [wcsrchr](../string/wide/wcsrchr "cpp/string/wide/wcsrchr") | finds the last occurrence of a wide character in a wide string (function) | | [wcsspn](../string/wide/wcsspn "cpp/string/wide/wcsspn") | returns the length of the maximum initial segment that consists of only the wide characters found in another wide string (function) | | [wcscspn](../string/wide/wcscspn "cpp/string/wide/wcscspn") | returns the length of the maximum initial segment that consists of only the wide *not* found in another wide string (function) | | [wcspbrk](../string/wide/wcspbrk "cpp/string/wide/wcspbrk") | finds the first location of any wide character in one wide string, in another wide string (function) | | [wcsstr](../string/wide/wcsstr "cpp/string/wide/wcsstr") | finds the first occurrence of a wide string within another wide string (function) | | [wcstok](../string/wide/wcstok "cpp/string/wide/wcstok") | finds the next token in a wide string (function) | | Wide character array manipulation | | [wmemcpy](../string/wide/wmemcpy "cpp/string/wide/wmemcpy") | copies a certain amount of wide characters between two non-overlapping arrays (function) | | [wmemmove](../string/wide/wmemmove "cpp/string/wide/wmemmove") | copies a certain amount of wide characters between two, possibly overlapping, arrays (function) | | [wmemcmp](../string/wide/wmemcmp "cpp/string/wide/wmemcmp") | compares a certain amount of wide characters from two arrays (function) | | [wmemchr](../string/wide/wmemchr "cpp/string/wide/wmemchr") | finds the first occurrence of a wide character in a wide character array (function) | | [wmemset](../string/wide/wmemset "cpp/string/wide/wmemset") | copies the given wide character to every position in a wide character array (function) | | Multibyte/wide character conversion | | [mbsinit](../string/multibyte/mbsinit "cpp/string/multibyte/mbsinit") | checks if the mbstate\_t object represents initial shift state (function) | | [btowc](../string/multibyte/btowc "cpp/string/multibyte/btowc") | widens a single-byte narrow character to wide character, if possible (function) | | [wctob](../string/multibyte/wctob "cpp/string/multibyte/wctob") | narrows a wide character to a single-byte narrow character, if possible (function) | | [mbrlen](../string/multibyte/mbrlen "cpp/string/multibyte/mbrlen") | returns the number of bytes in the next multibyte character, given state (function) | | [mbrtowc](../string/multibyte/mbrtowc "cpp/string/multibyte/mbrtowc") | converts the next multibyte character to wide character, given state (function) | | [wcrtomb](../string/multibyte/wcrtomb "cpp/string/multibyte/wcrtomb") | converts a wide character to its multibyte representation, given state (function) | | [mbsrtowcs](../string/multibyte/mbsrtowcs "cpp/string/multibyte/mbsrtowcs") | converts a narrow multibyte character string to wide string, given state (function) | | [wcsrtombs](../string/multibyte/wcsrtombs "cpp/string/multibyte/wcsrtombs") | converts a wide string to narrow multibyte character string, given state (function) | | Input/Output | | [fgetwcgetwc](../io/c/fgetwc "cpp/io/c/fgetwc") | gets a wide character from a file stream (function) | | [fgetws](../io/c/fgetws "cpp/io/c/fgetws") | gets a wide string from a file stream (function) | | [fputwcputwc](../io/c/fputwc "cpp/io/c/fputwc") | writes a wide character to a file stream (function) | | [fputws](../io/c/fputws "cpp/io/c/fputws") | writes a wide string to a file stream (function) | | [getwchar](../io/c/getwchar "cpp/io/c/getwchar") | reads a wide character from `[stdin](../io/c/std_streams "cpp/io/c/std streams")` (function) | | [putwchar](../io/c/putwchar "cpp/io/c/putwchar") | writes a wide character to `[stdout](../io/c/std_streams "cpp/io/c/std streams")` (function) | | [ungetwc](../io/c/ungetwc "cpp/io/c/ungetwc") | puts a wide character back into a file stream (function) | | [fwide](../io/c/fwide "cpp/io/c/fwide") | switches a file stream between wide character I/O and narrow character I/O (function) | | [wscanffwscanfswscanf](../io/c/fwscanf "cpp/io/c/fwscanf") | reads formatted wide character input from `[stdin](../io/c/std_streams "cpp/io/c/std streams")`, a file stream or a buffer (function) | | [vwscanfvfwscanfvswscanf](../io/c/vfwscanf "cpp/io/c/vfwscanf") (C++11)(C++11)(C++11) | reads formatted wide character input from `[stdin](../io/c/std_streams "cpp/io/c/std streams")`, a file stream or a buffer using variable argument list (function) | | [wprintffwprintfswprintf](../io/c/fwprintf "cpp/io/c/fwprintf") | prints formatted wide character output to `[stdout](../io/c/std_streams "cpp/io/c/std streams")`, a file stream or a buffer (function) | | [vwprintfvfwprintfvswprintf](../io/c/vfwprintf "cpp/io/c/vfwprintf") | prints formatted wide character output to `[stdout](../io/c/std_streams "cpp/io/c/std streams")`, a file stream or a buffer using variable argument list (function) | | String conversions | | [wcsftime](../chrono/c/wcsftime "cpp/chrono/c/wcsftime") | converts a `[std::tm](../chrono/c/tm "cpp/chrono/c/tm")` object to custom wide string textual representation (function) | | [wcstolwcstoll](../string/wide/wcstol "cpp/string/wide/wcstol") | converts a wide string to an integer value (function) | | [wcstoulwcstoull](../string/wide/wcstoul "cpp/string/wide/wcstoul") | converts a wide string to an unsigned integer value (function) | | [wcstofwcstodwcstold](../string/wide/wcstof "cpp/string/wide/wcstof") | converts a wide string to a floating point value (function) | ### Notes * `[NULL](../types/null "cpp/types/NULL")` is also defined in the following headers: + [`<cstddef>`](cstddef "cpp/header/cstddef") + [`<cstring>`](cstring "cpp/header/cstring") + [`<ctime>`](ctime "cpp/header/ctime") + [`<clocale>`](clocale "cpp/header/clocale") + [`<cstdio>`](cstdio "cpp/header/cstdio") * `[std::size\_t](../types/size_t "cpp/types/size t")` is also defined in the following headers: + [`<cstddef>`](cstddef "cpp/header/cstddef") + [`<ctime>`](ctime "cpp/header/ctime") + [`<cstdio>`](cstdio "cpp/header/cstdio") * `std::wint_t` is also defined in the following headers: + [`<cwctype>`](cwctype "cpp/header/cwctype") * `[std::tm](../chrono/c/tm "cpp/chrono/c/tm")` is also defined in the following headers: + [`<ctime>`](ctime "cpp/header/ctime") cpp Standard library header <typeinfo> Standard library header <typeinfo> ================================== This header is part of the [type support](../types "cpp/types") library. ### Classes | | | | --- | --- | | [type\_info](../types/type_info "cpp/types/type info") | contains some type's information, generated by the implementation. This is the class returned by the [`typeid`](../language/typeid "cpp/language/typeid") operator. (class) | | [bad\_typeid](../types/bad_typeid "cpp/types/bad typeid") | exception that is thrown if an argument in a [typeid expression](../language/typeid "cpp/language/typeid") is null (class) | | [bad\_cast](../types/bad_cast "cpp/types/bad cast") | exception that is thrown by an invalid [`dynamic_cast`](../language/dynamic_cast "cpp/language/dynamic cast") expression, i.e. a cast of reference type fails (class) | ### Synopsis ``` namespace std { class type_info; class bad_cast; class bad_typeid; } ``` #### Class `[std::type\_info](../types/type_info "cpp/types/type info")` ``` namespace std { class type_info { public: virtual ~type_info(); constexpr bool operator==(const type_info& rhs) const noexcept; bool before(const type_info& rhs) const noexcept; size_t hash_code() const noexcept; const char* name() const noexcept; type_info(const type_info&) = delete; // cannot be copied type_info& operator=(const type_info&) = delete; // cannot be copied }; } ``` #### Class `[std::bad\_cast](../types/bad_cast "cpp/types/bad cast")` ``` namespace std { class bad_cast : public exception { public: // see [exception] for the specification of the special member functions const char* what() const noexcept override; }; } ``` #### Class `[std::bad\_typeid](../types/bad_typeid "cpp/types/bad typeid")` ``` namespace std { class bad_typeid : public exception { public: // see [exception] for the specification of the special member functions const char* what() const noexcept override; }; } ``` cpp Standard library header <expected> (C++23) Standard library header <expected> (C++23) ========================================== This header is part of the [general utility](../utility "cpp/utility") library. | | | --- | | Classes | | [expected](../utility/expected "cpp/utility/expected") (C++23) | a wrapper that contains either an expected or error value (class template) | | [unexpected](../utility/expected/unexpected "cpp/utility/expected/unexpected") (C++23) | represented as an unexpected value in expected (class template) | | [bad\_expected\_access](../utility/expected/bad_expected_access "cpp/utility/expected/bad expected access") (C++23) | exception indicating checked access to an expected that contains an unexpected value (class template) | | [unexpect\_t](https://en.cppreference.com/mwiki/index.php?title=cpp/utility/expected/unexpect_t&action=edit&redlink=1 "cpp/utility/expected/unexpect t (page does not exist)") (C++23) | in-place construction tag for unexpected value in expected (class) | | Constants | | [unexpect](https://en.cppreference.com/mwiki/index.php?title=cpp/utility/expected/unexpect&action=edit&redlink=1 "cpp/utility/expected/unexpect (page does not exist)") (C++23) | object of type `unexpect_t` (constant) | ### Synopsis ``` namespace std { // class template unexpected template<class E> class unexpected; // class template bad_expected_access template<class E> class bad_expected_access // specialization of bad_expected_access for void template<> class bad_expected_access<void>; // in-place construction of unexpected values struct unexpect_t { explicit unexpect_t() = default; }; inline constexpr unexpect_t unexpect{}; // class template expected template<class T, class E> class expected; // partial specialization of expected for void types template<class T, class E> requires is_void_v<T> class expected<T, E>; } ``` #### Class template `std::unexpected` ``` namespace std { template<class E> class unexpected { public: // constructors constexpr unexpected(const unexpected&) = default; constexpr unexpected(unexpected&&) = default; template<class... Args> constexpr explicit unexpected(in_place_t, Args&&...); template<class U, class... Args> constexpr explicit unexpected(in_place_t, initializer_list<U>, Args&&...); template<class Err = E> constexpr explicit unexpected(Err&&); // assignment constexpr unexpected& operator=(const unexpected&) = default; constexpr unexpected& operator=(unexpected&&) = default; // observer constexpr const E& error() const& noexcept; constexpr E& error() & noexcept; constexpr const E&& error() const&& noexcept; constexpr E&& error() && noexcept; // swap constexpr void swap(unexpected& other) noexcept(/* see description */); friend constexpr void swap(unexpected& x, unexpected& y) noexcept(noexcept(x.swap(y))); // equality operator template<class E2> friend constexpr bool operator==(const unexpected&, const unexpected<E2>&); private: E unex; // exposition only }; template<class E> unexpected(E) -> unexpected<E>; } ``` #### Class template `std::bad_expected_access` ``` namespace std { template<class E> class bad_expected_access : public bad_expected_access<void> { public: // explicit constructor explicit bad_expected_access(E); // observers const char* what() const noexcept override; E& error() & noexcept; const E& error() const& noexcept; E&& error() && noexcept; const E&& error() const&& noexcept; private: E unex; // exposition only }; } ``` #### Class template specialization `std::bad_expected_access<void>` ``` namespace std { template<> class bad_expected_access<void> : public exception { protected: // constructors bad_expected_access() noexcept; bad_expected_access(const bad_expected_access&); bad_expected_access(bad_expected_access&&); bad_expected_access& operator=(const bad_expected_access&); bad_expected_access& operator=(bad_expected_access&&); ~bad_expected_access(); public: const char* what() const noexcept override; }; } ``` #### Class template `std::expected` ``` namespace std { template<class T, class E> class expected { public: using value_type = T; using error_type = E; using unexpected_type = unexpected<E>; template<class U> using rebind = expected<U, error_type>; // constructors constexpr expected(); constexpr explicit(/* see description */) expected(const expected&); constexpr explicit(/* see description */) expected(expected&&) noexcept(/* see description */); template<class U, class G> constexpr explicit(/* see description */) expected(const expected<U, G>&); template<class U, class G> constexpr explicit(/* see description */) expected(expected<U, G>&&); template<class U = T> constexpr explicit(/* see description */) expected(U&& v); template<class G> constexpr expected(const unexpected<G>&); template<class G> constexpr expected(unexpected<G>&&); template<class... Args> constexpr explicit expected(in_place_t, Args&&...); template<class U, class... Args> constexpr explicit expected(in_place_t, initializer_list<U>, Args&&...); template<class... Args> constexpr explicit expected(unexpect_t, Args&&...); template<class U, class... Args> constexpr explicit expected(unexpect_t, initializer_list<U>, Args&&...); // destructor constexpr ~expected(); // assignment constexpr expected& operator=(const expected&); constexpr expected& operator=(expected&&) noexcept(/* see description */); template<class U = T> constexpr expected& operator=(U&&); template<class G> constexpr expected& operator=(const unexpected<G>&); template<class G> constexpr expected& operator=(unexpected<G>&&); template<class... Args> constexpr T& emplace(Args&&...) noexcept; template<class U, class... Args> constexpr T& emplace(initializer_list<U>, Args&&...) noexcept; // swap constexpr void swap(expected&) noexcept(/* see description */); friend constexpr void swap(expected&, expected&) noexcept(/* see description */); // observers constexpr const T* operator->() const noexcept; constexpr T* operator->() noexcept; constexpr const T& operator*() const& noexcept; constexpr T& operator*() & noexcept; constexpr const T&& operator*() const&& noexcept; constexpr T&& operator*() && noexcept; constexpr explicit operator bool() const noexcept; constexpr bool has_value() const noexcept; constexpr const T& value() const&; constexpr T& value() &; constexpr const T&& value() const&&; constexpr T&& value() &&; constexpr const E& error() const&; constexpr E& error() &; constexpr const E&& error() const&&; constexpr E&& error() &&; template<class U> constexpr T value_or(U&&) const&; template<class U> constexpr T value_or(U&&) &&; // equality operators template<class T2, class E2> friend constexpr bool operator==(const expected& x, const expected<T2, E2>& y); template<class T2> friend constexpr bool operator==(const expected&, const T2&); template<class E2> friend constexpr bool operator==(const expected&, const unexpected<E2>&); private: bool has_val; // exposition only union { T val; // exposition only E unex; // exposition only }; }; } ``` #### Partial specialization of `std::expected` for `void` types ``` namespace std { template<class T, class E> requires is_void_v<T> class expected<T, E> { public: using value_type = T; using error_type = E; using unexpected_type = unexpected<E>; template<class U> using rebind = expected<U, error_type>; // constructors constexpr expected() noexcept; constexpr explicit(/* see description */) expected(const expected&); constexpr explicit(/* see description */) expected(expected&&) noexcept(/* see description */); template<class U, class G> constexpr explicit(/* see description */) expected(const expected<U, G>&); template<class U, class G> constexpr explicit(/* see description */) expected(expected<U, G>&&); template<class G> constexpr expected(const unexpected<G>&); template<class G> constexpr expected(unexpected<G>&&); constexpr explicit expected(in_place_t) noexcept; template<class... Args> constexpr explicit expected(unexpect_t, Args&&...); template<class U, class... Args> constexpr explicit expected(unexpect_t, initializer_list<U>, Args&&...); // destructor constexpr ~expected(); // assignment constexpr expected& operator=(const expected&); constexpr expected& operator=(expected&&) noexcept(/* see description */); template<class G> constexpr expected& operator=(const unexpected<G>&); template<class G> constexpr expected& operator=(unexpected<G>&&); constexpr void emplace() noexcept; // swap constexpr void swap(expected&) noexcept(/* see description */); friend constexpr void swap(expected&, expected&) noexcept(/* see description */); // observers constexpr explicit operator bool() const noexcept; constexpr bool has_value() const noexcept; constexpr void operator*() const noexcept; constexpr void value() const&; constexpr void value() &&; constexpr const E& error() const&; constexpr E& error() &; constexpr const E&& error() const&&; constexpr E&& error() &&; // equality operators template<class T2, class E2> requires is_void_v<T2> friend constexpr bool operator==(const expected& x, const expected<T2, E2>& y); template<class E2> friend constexpr bool operator==(const expected&, const unexpected<E2>&); private: bool has_val; // exposition only union { E unex; // exposition only }; }; } ```
programming_docs
cpp Standard library header <thread> (C++11) Standard library header <thread> (C++11) ======================================== This header is part of the [thread support](../thread "cpp/thread") library. | | | --- | | Includes | | [<compare>](compare "cpp/header/compare") (C++20) | [Three-way comparison operator](../language/operator_comparison#Three-way_comparison "cpp/language/operator comparison") support | | Namespaces | | `this_thread` | provide functions that access the current thread of execution | | Classes | | [thread](../thread/thread "cpp/thread/thread") (C++11) | manages a separate thread (class) | | [jthread](../thread/jthread "cpp/thread/jthread") (C++20) | `[std::thread](../thread/thread "cpp/thread/thread")` with support for auto-joining and cancellation (class) | | [std::hash<std::thread::id>](../thread/thread/id/hash "cpp/thread/thread/id/hash") | specializes `[std::hash](../utility/hash "cpp/utility/hash")` (class template specialization) | | Functions | | [std::swap(std::thread)](../thread/thread/swap2 "cpp/thread/thread/swap2") (C++11) | specializes the `[std::swap](../algorithm/swap "cpp/algorithm/swap")` algorithm (function) | | [operator==operator!=operator< operator<= operator> operator>= operator<=>](../thread/thread/id/operator_cmp "cpp/thread/thread/id/operator cmp") (removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(C++20) | compares two `thread::id` objects (function) | | [operator<<](../thread/thread/id/operator_ltlt "cpp/thread/thread/id/operator ltlt") | serializes a `thread::id` object (function template) | | Defined in namespace `std::this_thread` | | [yield](../thread/yield "cpp/thread/yield") (C++11) | suggests that the implementation reschedule execution of threads (function) | | [get\_id](../thread/get_id "cpp/thread/get id") (C++11) | returns the thread id of the current thread (function) | | [sleep\_for](../thread/sleep_for "cpp/thread/sleep for") (C++11) | stops the execution of the current thread for a specified time duration (function) | | [sleep\_until](../thread/sleep_until "cpp/thread/sleep until") (C++11) | stops the execution of the current thread until a specified time point (function) | ### Synopsis ``` #include <compare> namespace std { class thread; void swap(thread& x, thread& y) noexcept; // class jthread class jthread; namespace this_thread { thread::id get_id() noexcept; void yield() noexcept; template<class Clock, class Duration> void sleep_until(const chrono::time_point<Clock, Duration>& abs_time); template<class Rep, class Period> void sleep_for(const chrono::duration<Rep, Period>& rel_time); } } ``` #### Class `[std::thread](../thread/thread "cpp/thread/thread")` ``` namespace std { class thread { public: // types class id; using native_handle_type = /* implementation-defined */; // construct/copy/destroy thread() noexcept; template<class F, class... Args> explicit thread(F&& f, Args&&... args); ~thread(); thread(const thread&) = delete; thread(thread&&) noexcept; thread& operator=(const thread&) = delete; thread& operator=(thread&&) noexcept; // members void swap(thread&) noexcept; bool joinable() const noexcept; void join(); void detach(); id get_id() const noexcept; native_handle_type native_handle(); // static members static unsigned int hardware_concurrency() noexcept; }; } ``` #### Class `[std::jthread](../thread/jthread "cpp/thread/jthread")` ``` namespace std { class jthread { public: // types using id = thread::id; using native_handle_type = thread::native_handle_type; // constructors, move, and assignment jthread() noexcept; template<class F, class... Args> explicit jthread(F&& f, Args&&... args); ~jthread(); jthread(const jthread&) = delete; jthread(jthread&&) noexcept; jthread& operator=(const jthread&) = delete; jthread& operator=(jthread&&) noexcept; // members void swap(jthread&) noexcept; [[nodiscard]] bool joinable() const noexcept; void join(); void detach(); [[nodiscard]] id get_id() const noexcept; [[nodiscard]] native_handle_type native_handle(); // stop token handling [[nodiscard]] stop_source get_stop_source() noexcept; [[nodiscard]] stop_token get_stop_token() const noexcept; bool request_stop() noexcept; // specialized algorithms friend void swap(jthread& lhs, jthread& rhs) noexcept; // static members [[nodiscard]] static unsigned int hardware_concurrency() noexcept; private: stop_source ssource; // exposition only }; } ``` #### Class `[std::thread::id](../thread/thread/id "cpp/thread/thread/id")` ``` namespace std { class thread::id { public: id() noexcept; }; bool operator==(thread::id x, thread::id y) noexcept; strong_ordering operator<=>(thread::id x, thread::id y) noexcept; template<class charT, class traits> basic_ostream<charT, traits>& operator<<(basic_ostream<charT, traits>& out, thread::id id); // hash support template<class T> struct hash; template<> struct hash<thread::id>; } ``` cpp Standard library header <stacktrace> (C++23) Standard library header <stacktrace> (C++23) ============================================ This header is part of the [general utility](../utility "cpp/utility") library. | | | --- | | Classes | | [stacktrace\_entry](../utility/stacktrace_entry "cpp/utility/stacktrace entry") (C++23) | representation of an evaluation in a stacktrace (class) | | [basic\_stacktrace](../utility/basic_stacktrace "cpp/utility/basic stacktrace") (C++23) | approximate representation of an invocation sequence consists of stacktrace entries (class template) | | [`std::stacktrace`](../utility/basic_stacktrace "cpp/utility/basic stacktrace") | `std::basic\_stacktrace<[std::allocator](http://en.cppreference.com/w/cpp/memory/allocator)<std::stacktrace\_entry>>` (typedef) | | [std::hash<std::stacktrace\_entry>](../utility/stacktrace_entry/hash "cpp/utility/stacktrace entry/hash") (C++23) | hash support for `std::stacktrace_entry` (class template specialization) | | [std::hash<std::basic\_stacktrace>](../utility/basic_stacktrace/hash "cpp/utility/basic stacktrace/hash") (C++23) | hash support for `std::basic_stacktrace` (class template specialization) | | Forward declarations | | Defined in header `[<functional>](functional "cpp/header/functional")` | | [hash](../utility/hash "cpp/utility/hash") (C++11) | hash function object (class template) | | Functions | | [std::swap(std::basic\_stacktrace)](../utility/basic_stacktrace/swap2 "cpp/utility/basic stacktrace/swap2") (C++23) | specializes the `[std::swap](../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | | [to\_string](../utility/stacktrace_entry/to_string "cpp/utility/stacktrace entry/to string") (C++23) | returns a string with a description of the `stacktrace_entry` (function) | | [to\_string](../utility/basic_stacktrace/to_string "cpp/utility/basic stacktrace/to string") (C++23) | returns a string with a description of the `basic_stacktrace` (function template) | | [operator<<](../utility/stacktrace_entry/operator_ltlt "cpp/utility/stacktrace entry/operator ltlt") (C++23) | performs stream output of `stacktrace_entry` (function template) | | [operator<<](../utility/basic_stacktrace/operator_ltlt "cpp/utility/basic stacktrace/operator ltlt") (C++23) | performs stream output of `basic_stracktrace` (function template) | ### Synopsis ``` namespace std { // class stacktrace_entry class stacktrace_entry; // class template basic_stacktrace template<class Allocator> class basic_stacktrace; // basic_stacktrace typedef names using stacktrace = basic_stacktrace<allocator<stacktrace_entry>>; // non-member functions template<class Allocator> void swap(basic_stacktrace<Allocator>& a, basic_stacktrace<Allocator>& b) noexcept(noexcept(a.swap(b))); string to_string(const stacktrace_entry& f); template<class Allocator> string to_string(const basic_stacktrace<Allocator>& st); template<class CharT, class Traits> basic_ostream<CharT, Traits>& operator<<(basic_ostream<CharT, Traits>& os, const stacktrace_entry& f); template<class CharT, class Traits, class Allocator> basic_ostream<CharT, Traits>& operator<<(basic_ostream<CharT, Traits>& os, const basic_stacktrace<Allocator>& st); namespace pmr { using stacktrace = std::basic_stacktrace<polymorphic_allocator<stacktrace_entry>>; } // hash support template<class T> struct hash; template<> struct hash<stacktrace_entry>; template<class Allocator> struct hash<basic_stacktrace<Allocator>>; } ``` #### Class `std::stacktrace_entry` ``` namespace std { class stacktrace_entry { public: using native_handle_type = /* implementation-defined */; // constructors constexpr stacktrace_entry() noexcept; constexpr stacktrace_entry(const stacktrace_entry& other) noexcept; constexpr stacktrace_entry& operator=(const stacktrace_entry& other) noexcept; ~stacktrace_entry(); // observers constexpr native_handle_type native_handle() const noexcept; constexpr explicit operator bool() const noexcept; // query string description() const; string source_file() const; uint_least32_t source_line() const; // comparison friend constexpr bool operator==(const stacktrace_entry& x, const stacktrace_entry& y) noexcept; friend constexpr strong_ordering operator<=>(const stacktrace_entry& x, const stacktrace_entry& y) noexcept; }; } ``` #### Class template `std::basic_stacktrace` ``` namespace std { template<class Allocator> class basic_stacktrace { public: using value_type = stacktrace_entry; using const_reference = const value_type&; using reference = value_type&; using const_iterator = /* implementation-defined */; using iterator = const_iterator; using reverse_iterator = std::reverse_iterator<iterator>; using const_reverse_iterator = std::reverse_iterator<const_iterator>; using difference_type = /* implementation-defined */; using size_type = /* implementation-defined */; using allocator_type = Allocator; // creation and assignment static basic_stacktrace current(const allocator_type& alloc = allocator_type()) noexcept; static basic_stacktrace current(size_type skip, const allocator_type& alloc = allocator_type()) noexcept; static basic_stacktrace current(size_type skip, size_type max_depth, const allocator_type& alloc = allocator_type()) noexcept; basic_stacktrace() noexcept(is_nothrow_default_constructible_v<allocator_type>); explicit basic_stacktrace(const allocator_type& alloc) noexcept; basic_stacktrace(const basic_stacktrace& other); basic_stacktrace(basic_stacktrace&& other) noexcept; basic_stacktrace(const basic_stacktrace& other, const allocator_type& alloc); basic_stacktrace(basic_stacktrace&& other, const allocator_type& alloc); basic_stacktrace& operator=(const basic_stacktrace& other); basic_stacktrace& operator=(basic_stacktrace&& other) noexcept( allocator_traits<Allocator>::propagate_on_container_move_assignment::value || allocator_traits<Allocator>::is_always_equal::value); ~basic_stacktrace(); // observers allocator_type get_allocator() const noexcept; const_iterator begin() const noexcept; const_iterator end() const noexcept; const_reverse_iterator rbegin() const noexcept; const_reverse_iterator rend() const noexcept; const_iterator cbegin() const noexcept; const_iterator cend() const noexcept; const_reverse_iterator crbegin() const noexcept; const_reverse_iterator crend() const noexcept; [[nodiscard]] bool empty() const noexcept; size_type size() const noexcept; size_type max_size() const noexcept; const_reference operator[](size_type) const; const_reference at(size_type) const; // comparisons template<class Allocator2> friend bool operator==(const basic_stacktrace& x, const basic_stacktrace<Allocator2>& y) noexcept; template<class Allocator2> friend strong_ordering operator<=>(const basic_stacktrace& x, const basic_stacktrace<Allocator2>& y) noexcept; // modifiers void swap(basic_stacktrace& other) noexcept(allocator_traits<Allocator>::propagate_on_container_swap::value || allocator_traits<Allocator>::is_always_equal::value); private: vector<value_type, allocator_type> frames_; // exposition only }; } ``` cpp Standard library header <stdexcept> Standard library header <stdexcept> =================================== This header is part of the [error handling](../error "cpp/error") library. | | | --- | | Classes | | [logic\_error](../error/logic_error "cpp/error/logic error") | exception class to indicate violations of logical preconditions or class invariants (class) | | [invalid\_argument](../error/invalid_argument "cpp/error/invalid argument") | exception class to report invalid arguments (class) | | [domain\_error](../error/domain_error "cpp/error/domain error") | exception class to report domain errors (class) | | [length\_error](../error/length_error "cpp/error/length error") | exception class to report attempts to exceed maximum allowed size (class) | | [out\_of\_range](../error/out_of_range "cpp/error/out of range") | exception class to report arguments outside of expected range (class) | | [runtime\_error](../error/runtime_error "cpp/error/runtime error") | exception class to indicate conditions only detectable at run time (class) | | [range\_error](../error/range_error "cpp/error/range error") | exception class to report range errors in internal computations (class) | | [overflow\_error](../error/overflow_error "cpp/error/overflow error") | exception class to report arithmetic overflows (class) | | [underflow\_error](../error/underflow_error "cpp/error/underflow error") | exception class to report arithmetic underflows (class) | ### Synopsis ``` namespace std { class logic_error; class domain_error; class invalid_argument; class length_error; class out_of_range; class runtime_error; class range_error; class overflow_error; class underflow_error; } ``` #### Class `[std::logic\_error](../error/logic_error "cpp/error/logic error")` ``` namespace std { class logic_error : public exception { public: explicit logic_error(const string& what_arg); explicit logic_error(const char* what_arg); }; } ``` #### Class `[std::domain\_error](../error/domain_error "cpp/error/domain error")` ``` namespace std { class domain_error : public logic_error { public: explicit domain_error(const string& what_arg); explicit domain_error(const char* what_arg); }; } ``` #### Class `[std::invalid\_argument](../error/invalid_argument "cpp/error/invalid argument")` ``` namespace std { class invalid_argument : public logic_error { public: explicit invalid_argument(const string& what_arg); explicit invalid_argument(const char* what_arg); }; } ``` #### Class `[std::length\_error](../error/length_error "cpp/error/length error")` ``` namespace std { class length_error : public logic_error { public: explicit length_error(const string& what_arg); explicit length_error(const char* what_arg); }; } ``` #### Class `[std::out\_of\_range](../error/out_of_range "cpp/error/out of range")` ``` namespace std { class out_of_range : public logic_error { public: explicit out_of_range(const string& what_arg); explicit out_of_range(const char* what_arg); }; } ``` #### Class `[std::runtime\_error](../error/runtime_error "cpp/error/runtime error")` ``` namespace std { class runtime_error : public exception { public: explicit runtime_error(const string& what_arg); explicit runtime_error(const char* what_arg); }; } ``` #### Class `[std::range\_error](../error/range_error "cpp/error/range error")` ``` namespace std { class range_error : public runtime_error { public: explicit range_error(const string& what_arg); explicit range_error(const char* what_arg); }; } ``` #### Class `[std::overflow\_error](../error/overflow_error "cpp/error/overflow error")` ``` namespace std { class overflow_error : public runtime_error { public: explicit overflow_error(const string& what_arg); explicit overflow_error(const char* what_arg); }; } ``` #### Class `[std::underflow\_error](../error/underflow_error "cpp/error/underflow error")` ``` namespace std { class underflow_error : public runtime_error { public: explicit underflow_error(const string& what_arg); explicit underflow_error(const char* what_arg); }; } ``` ### See also | | | | --- | --- | | [exception](../error/exception "cpp/error/exception") | base class for exceptions thrown by the standard library components (class) | cpp Standard library header <cfenv> (C++11) Standard library header <cfenv> (C++11) ======================================= This header was originally in the C standard library as `<fenv.h>`. This header is part of the [floating-point environment](../numeric/fenv "cpp/numeric/fenv") library. ### Types | | | | --- | --- | | `fenv_t` | The type representing the entire floating-point environment | | `fexcept_t` | The type representing all floating-point status flags collectively | ### Functions | | | | --- | --- | | [feclearexcept](../numeric/fenv/feclearexcept "cpp/numeric/fenv/feclearexcept") (C++11) | clears the specified floating-point status flags (function) | | [fetestexcept](../numeric/fenv/fetestexcept "cpp/numeric/fenv/fetestexcept") (C++11) | determines which of the specified floating-point status flags are set (function) | | [feraiseexcept](../numeric/fenv/feraiseexcept "cpp/numeric/fenv/feraiseexcept") (C++11) | raises the specified floating-point exceptions (function) | | [fegetexceptflagfesetexceptflag](../numeric/fenv/feexceptflag "cpp/numeric/fenv/feexceptflag") (C++11)(C++11) | copies the state of the specified floating-point status flags from or to the floating-point environment (function) | | [fegetroundfesetround](../numeric/fenv/feround "cpp/numeric/fenv/feround") (C++11)(C++11) | gets or sets rounding direction (function) | | [fegetenvfesetenv](../numeric/fenv/feenv "cpp/numeric/fenv/feenv") (C++11) | saves or restores the current floating-point environment (function) | | [feholdexcept](../numeric/fenv/feholdexcept "cpp/numeric/fenv/feholdexcept") (C++11) | saves the environment, clears all status flags and ignores all future errors (function) | | [feupdateenv](../numeric/fenv/feupdateenv "cpp/numeric/fenv/feupdateenv") (C++11) | restores the floating-point environment and raises the previously raise exceptions (function) | ### Macros | | | | --- | --- | | [FE\_ALL\_EXCEPTFE\_DIVBYZEROFE\_INEXACTFE\_INVALIDFE\_OVERFLOWFE\_UNDERFLOW](../numeric/fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions") (C++11) | floating-point exceptions (macro constant) | | [FE\_DOWNWARDFE\_TONEARESTFE\_TOWARDZEROFE\_UPWARD](../numeric/fenv/fe_round "cpp/numeric/fenv/FE round") (C++11) | floating-point rounding direction (macro constant) | | [FE\_DFL\_ENV](../numeric/fenv/fe_dfl_env "cpp/numeric/fenv/FE DFL ENV") (C++11) | default floating-point environment (macro constant) | ### Synopsis ``` namespace std { // types typedef /*object type*/ fenv_t; typedef /*integer type*/ fexcept_t; // functions int feclearexcept(int except); int fegetexceptflag(fexcept_t *pflag, int except); int feraiseexcept(int except); int fesetexceptflag(const fexcept_t *pflag, int except); int fetestexcept(int except); int fegetround(void); int fesetround(int mode); int fegetenv(fenv_t *penv); int feholdexcept(fenv_t *penv); int fesetenv(const fenv_t *penv); int feupdateenv(const fenv_t *penv); } ```
programming_docs
cpp Standard library header <csignal> Standard library header <csignal> ================================= This header was originally in the C standard library as `<signal.h>`. This header is part of the [program support](../utility/program "cpp/utility/program") library. | | | --- | | Typedefs | | [sig\_atomic\_t](../utility/program/sig_atomic_t "cpp/utility/program/sig atomic t") | the integer type that can be accessed as an atomic entity from an asynchronous signal handler (typedef) | | Macros | | [SIGABRTSIGFPESIGILLSIGINTSIGSEGVSIGTERM](../utility/program/sig_types "cpp/utility/program/SIG types") | defines signal types (macro constant) | | [SIG\_DFLSIG\_IGN](../utility/program/sig_strategies "cpp/utility/program/SIG strategies") | defines signal handling strategies (macro constant) | | [SIG\_ERR](../utility/program/sig_err "cpp/utility/program/SIG ERR") | return value of [`signal`](../utility/program/signal "cpp/utility/program/signal") specifying that an error was encountered (macro constant) | | Functions | | [signal](../utility/program/signal "cpp/utility/program/signal") | sets a signal handler for particular signal (function) | | [raise](../utility/program/raise "cpp/utility/program/raise") | runs the signal handler for particular signal (function) | ### Synopsis ``` namespace std { using sig_atomic_t = /*see description*/ ; extern "C" using /*signal-handler*/ = void(int); // exposition only /*signal-handler*/ * signal(int sig, /*signal-handler*/ * func); } #define SIG_DFL /*see description*/ #define SIG_ERR /*see description*/ #define SIG_IGN /*see description*/ #define SIGABRT /*see description*/ #define SIGFPE /*see description*/ #define SIGILL /*see description*/ #define SIGINT /*see description*/ #define SIGSEGV /*see description*/ #define SIGTERM /*see description*/ ``` cpp Standard library header <set> Standard library header <set> ============================= This header is part of the [containers](../container "cpp/container") library. | | | --- | | Includes | | [<compare>](compare "cpp/header/compare") (C++20) | [Three-way comparison operator](../language/operator_comparison#Three-way_comparison "cpp/language/operator comparison") support | | [<initializer\_list>](initializer_list "cpp/header/initializer list") (C++11) | `[std::initializer\_list](../utility/initializer_list "cpp/utility/initializer list")` class template | | Classes | | [set](../container/set "cpp/container/set") | collection of unique keys, sorted by keys (class template) | | [multiset](../container/multiset "cpp/container/multiset") | collection of keys, sorted by keys (class template) | | Functions | | [operator==operator!=operator<operator<=operator>operator>=operator<=>](../container/set/operator_cmp "cpp/container/set/operator cmp") (removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(C++20) | lexicographically compares the values in the set (function template) | | [std::swap(std::set)](../container/set/swap2 "cpp/container/set/swap2") | specializes the `[std::swap](../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | | [erase\_if(std::set)](../container/set/erase_if "cpp/container/set/erase if") (C++20) | Erases all elements satisfying specific criteria (function template) | | [operator==operator!=operator<operator<=operator>operator>=operator<=>](../container/multiset/operator_cmp "cpp/container/multiset/operator cmp") (removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(C++20) | lexicographically compares the values in the multiset (function template) | | [std::swap(std::multiset)](../container/multiset/swap2 "cpp/container/multiset/swap2") | specializes the `[std::swap](../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | | [erase\_if(std::multiset)](../container/multiset/erase_if "cpp/container/multiset/erase if") (C++20) | Erases all elements satisfying specific criteria (function template) | | Range access | | [begincbegin](../iterator/begin "cpp/iterator/begin") (C++11)(C++14) | returns an iterator to the beginning of a container or array (function template) | | [endcend](../iterator/end "cpp/iterator/end") (C++11)(C++14) | returns an iterator to the end of a container or array (function template) | | [rbegincrbegin](../iterator/rbegin "cpp/iterator/rbegin") (C++14) | returns a reverse iterator to the beginning of a container or array (function template) | | [rendcrend](../iterator/rend "cpp/iterator/rend") (C++14) | returns a reverse end iterator for a container or array (function template) | | [sizessize](../iterator/size "cpp/iterator/size") (C++17)(C++20) | returns the size of a container or array (function template) | | [empty](../iterator/empty "cpp/iterator/empty") (C++17) | checks whether the container is empty (function template) | | [data](../iterator/data "cpp/iterator/data") (C++17) | obtains the pointer to the underlying array (function template) | ### Synopsis ``` #include <compare> #include <initializer_list> namespace std { // class template set template<class Key, class Compare = less<Key>, class Allocator = allocator<Key>> class set; template<class Key, class Compare, class Allocator> bool operator==(const set<Key, Compare, Allocator>& x, const set<Key, Compare, Allocator>& y); template<class Key, class Compare, class Allocator> /*synth-three-way-result*/<Key> operator<=>(const set<Key, Compare, Allocator>& x, const set<Key, Compare, Allocator>& y); template<class Key, class Compare, class Allocator> void swap(set<Key, Compare, Allocator>& x, set<Key, Compare, Allocator>& y) noexcept(noexcept(x.swap(y))); template<class Key, class Compare, class Allocator, class Predicate> typename set<Key, Compare, Allocator>::size_type erase_if(set<Key, Compare, Allocator>& c, Predicate pred); // class template multiset template<class Key, class Compare = less<Key>, class Allocator = allocator<Key>> class multiset; template<class Key, class Compare, class Allocator> bool operator==(const multiset<Key, Compare, Allocator>& x, const multiset<Key, Compare, Allocator>& y); template<class Key, class Compare, class Allocator> /*synth-three-way-result*/<Key> operator<=>(const multiset<Key, Compare, Allocator>& x, const multiset<Key, Compare, Allocator>& y); template<class Key, class Compare, class Allocator> void swap(multiset<Key, Compare, Allocator>& x, multiset<Key, Compare, Allocator>& y) noexcept(noexcept(x.swap(y))); template<class Key, class Compare, class Allocator, class Predicate> typename multiset<Key, Compare, Allocator>::size_type erase_if(multiset<Key, Compare, Allocator>& c, Predicate pred); namespace pmr { template<class Key, class Compare = less<Key>> using set = std::set<Key, Compare, polymorphic_allocator<Key>>; template<class Key, class Compare = less<Key>> using multiset = std::multiset<Key, Compare, polymorphic_allocator<Key>>; } } ``` #### Class template `[std::set](../container/set "cpp/container/set")` ``` namespace std { template<class Key, class Compare = less<Key>, class Allocator = allocator<Key>> class set { public: // types using key_type = Key; using key_compare = Compare; using value_type = Key; using value_compare = Compare; using allocator_type = Allocator; using pointer = typename allocator_traits<Allocator>::pointer; using const_pointer = typename allocator_traits<Allocator>::const_pointer; using reference = value_type&; using const_reference = const value_type&; using size_type = /* implementation-defined */; using difference_type = /* implementation-defined */; using iterator = /* implementation-defined */; using const_iterator = /* implementation-defined */; using reverse_iterator = std::reverse_iterator<iterator>; using const_reverse_iterator = std::reverse_iterator<const_iterator>; using node_type = /* unspecified */; using insert_return_type = /*insert-return-type*/<iterator, node_type>; // construct/copy/destroy set() : set(Compare()) { } explicit set(const Compare& comp, const Allocator& = Allocator()); template<class InputIt> set(InputIt first, InputIt last, const Compare& comp = Compare(), const Allocator& = Allocator()); set(const set& x); set(set&& x); explicit set(const Allocator&); set(const set&, const Allocator&); set(set&&, const Allocator&); set(initializer_list<value_type>, const Compare& = Compare(), const Allocator& = Allocator()); template<class InputIt> set(InputIt first, InputIt last, const Allocator& a) : set(first, last, Compare(), a) { } set(initializer_list<value_type> il, const Allocator& a) : set(il, Compare(), a) { } ~set(); set& operator=(const set& x); set& operator=(set&& x) noexcept(allocator_traits<Allocator>::is_always_equal::value && is_nothrow_move_assignable_v<Compare>); set& operator=(initializer_list<value_type>); allocator_type get_allocator() const noexcept; // iterators iterator begin() noexcept; const_iterator begin() const noexcept; iterator end() noexcept; const_iterator end() const noexcept; reverse_iterator rbegin() noexcept; const_reverse_iterator rbegin() const noexcept; reverse_iterator rend() noexcept; const_reverse_iterator rend() const noexcept; const_iterator cbegin() const noexcept; const_iterator cend() const noexcept; const_reverse_iterator crbegin() const noexcept; const_reverse_iterator crend() const noexcept; // capacity [[nodiscard]] bool empty() const noexcept; size_type size() const noexcept; size_type max_size() const noexcept; // modifiers template<class... Args> pair<iterator, bool> emplace(Args&&... args); template<class... Args> iterator emplace_hint(const_iterator position, Args&&... args); pair<iterator,bool> insert(const value_type& x); pair<iterator,bool> insert(value_type&& x); iterator insert(const_iterator position, const value_type& x); iterator insert(const_iterator position, value_type&& x); template<class InputIt> void insert(InputIt first, InputIt last); void insert(initializer_list<value_type>); node_type extract(const_iterator position); node_type extract(const key_type& x); template<class K> node_type extract(K&& x); insert_return_type insert(node_type&& nh); iterator insert(const_iterator hint, node_type&& nh); iterator erase(iterator position); iterator erase(const_iterator position); size_type erase(const key_type& x); template<class K> size_type erase(K&& x); iterator erase(const_iterator first, const_iterator last); void swap(set&) noexcept(allocator_traits<Allocator>::is_always_equal::value && is_nothrow_swappable_v<Compare>); void clear() noexcept; template<class C2> void merge(set<Key, C2, Allocator>& source); template<class C2> void merge(set<Key, C2, Allocator>&& source); template<class C2> void merge(multiset<Key, C2, Allocator>& source); template<class C2> void merge(multiset<Key, C2, Allocator>&& source); // observers key_compare key_comp() const; value_compare value_comp() const; // set operations iterator find(const key_type& x); const_iterator find(const key_type& x) const; template<class K> iterator find(const K& x); template<class K> const_iterator find(const K& x) const; size_type count(const key_type& x) const; template<class K> size_type count(const K& x) const; bool contains(const key_type& x) const; template<class K> bool contains(const K& x) const; iterator lower_bound(const key_type& x); const_iterator lower_bound(const key_type& x) const; template<class K> iterator lower_bound(const K& x); template<class K> const_iterator lower_bound(const K& x) const; iterator upper_bound(const key_type& x); const_iterator upper_bound(const key_type& x) const; template<class K> iterator upper_bound(const K& x); template<class K> const_iterator upper_bound(const K& x) const; pair<iterator, iterator> equal_range(const key_type& x); pair<const_iterator, const_iterator> equal_range(const key_type& x) const; template<class K> pair<iterator, iterator> equal_range(const K& x); template<class K> pair<const_iterator, const_iterator> equal_range(const K& x) const; }; template<class InputIt, class Compare = less</*iter-value-type*/<InputIt>>, class Allocator = allocator</*iter-value-type*/<InputIt>>> set(InputIt, InputIt, Compare = Compare(), Allocator = Allocator()) -> set</*iter-value-type*/<InputIt>, Compare, Allocator>; template<class Key, class Compare = less<Key>, class Allocator = allocator<Key>> set(initializer_list<Key>, Compare = Compare(), Allocator = Allocator()) -> set<Key, Compare, Allocator>; template<class InputIt, class Allocator> set(InputIt, InputIt, Allocator) -> set</*iter-value-type*/<InputIt>, less</*iter-value-type*/<InputIt>>, Allocator>; template<class Key, class Allocator> set(initializer_list<Key>, Allocator) -> set<Key, less<Key>, Allocator>; // swap template<class Key, class Compare, class Allocator> void swap(set<Key, Compare, Allocator>& x, set<Key, Compare, Allocator>& y) noexcept(noexcept(x.swap(y))); } ``` #### Class template `[std::multiset](../container/multiset "cpp/container/multiset")` ``` namespace std { template<class Key, class Compare = less<Key>, class Allocator = allocator<Key>> class multiset { public: // types using key_type = Key; using key_compare = Compare; using value_type = Key; using value_compare = Compare; using allocator_type = Allocator; using pointer = typename allocator_traits<Allocator>::pointer; using const_pointer = typename allocator_traits<Allocator>::const_pointer; using reference = value_type&; using const_reference = const value_type&; using size_type = /* implementation-defined */; using difference_type = /* implementation-defined */; using iterator = /* implementation-defined */; using const_iterator = /* implementation-defined */; using reverse_iterator = std::reverse_iterator<iterator>; using const_reverse_iterator = std::reverse_iterator<const_iterator>; using node_type = /* unspecified */; // construct/copy/destroy multiset() : multiset(Compare()) { } explicit multiset(const Compare& comp, const Allocator& = Allocator()); template<class InputIt> multiset(InputIt first, InputIt last, const Compare& comp = Compare(), const Allocator& = Allocator()); multiset(const multiset& x); multiset(multiset&& x); explicit multiset(const Allocator&); multiset(const multiset&, const Allocator&); multiset(multiset&&, const Allocator&); multiset(initializer_list<value_type>, const Compare& = Compare(), const Allocator& = Allocator()); template<class InputIt> multiset(InputIt first, InputIt last, const Allocator& a) : multiset(first, last, Compare(), a) { } multiset(initializer_list<value_type> il, const Allocator& a) : multiset(il, Compare(), a) { } ~multiset(); multiset& operator=(const multiset& x); multiset& operator=(multiset&& x) noexcept(allocator_traits<Allocator>::is_always_equal::value && is_nothrow_move_assignable_v<Compare>); multiset& operator=(initializer_list<value_type>); allocator_type get_allocator() const noexcept; // iterators iterator begin() noexcept; const_iterator begin() const noexcept; iterator end() noexcept; const_iterator end() const noexcept; reverse_iterator rbegin() noexcept; const_reverse_iterator rbegin() const noexcept; reverse_iterator rend() noexcept; const_reverse_iterator rend() const noexcept; const_iterator cbegin() const noexcept; const_iterator cend() const noexcept; const_reverse_iterator crbegin() const noexcept; const_reverse_iterator crend() const noexcept; // capacity [[nodiscard]] bool empty() const noexcept; size_type size() const noexcept; size_type max_size() const noexcept; // modifiers template<class... Args> iterator emplace(Args&&... args); template<class... Args> iterator emplace_hint(const_iterator position, Args&&... args); iterator insert(const value_type& x); iterator insert(value_type&& x); iterator insert(const_iterator position, const value_type& x); iterator insert(const_iterator position, value_type&& x); template<class InputIt> void insert(InputIt first, InputIt last); void insert(initializer_list<value_type>); node_type extract(const_iterator position); node_type extract(const key_type& x); template<class K> node_type extract(K&& x); iterator insert(node_type&& nh); iterator insert(const_iterator hint, node_type&& nh); iterator erase(iterator position); iterator erase(const_iterator position); size_type erase(const key_type& x); template<class K> size_type erase(K&& x); iterator erase(const_iterator first, const_iterator last); void swap(multiset&) noexcept(allocator_traits<Allocator>::is_always_equal::value && is_nothrow_swappable_v<Compare>); void clear() noexcept; template<class C2> void merge(multiset<Key, C2, Allocator>& source); template<class C2> void merge(multiset<Key, C2, Allocator>&& source); template<class C2> void merge(set<Key, C2, Allocator>& source); template<class C2> void merge(set<Key, C2, Allocator>&& source); // observers key_compare key_comp() const; value_compare value_comp() const; // set operations iterator find(const key_type& x); const_iterator find(const key_type& x) const; template<class K> iterator find(const K& x); template<class K> const_iterator find(const K& x) const; size_type count(const key_type& x) const; template<class K> size_type count(const K& x) const; bool contains(const key_type& x) const; template<class K> bool contains(const K& x) const; iterator lower_bound(const key_type& x); const_iterator lower_bound(const key_type& x) const; template<class K> iterator lower_bound(const K& x); template<class K> const_iterator lower_bound(const K& x) const; iterator upper_bound(const key_type& x); const_iterator upper_bound(const key_type& x) const; template<class K> iterator upper_bound(const K& x); template<class K> const_iterator upper_bound(const K& x) const; pair<iterator, iterator> equal_range(const key_type& x); pair<const_iterator, const_iterator> equal_range(const key_type& x) const; template<class K> pair<iterator, iterator> equal_range(const K& x); template<class K> pair<const_iterator, const_iterator> equal_range(const K& x) const; }; template<class InputIt, class Compare = less</*iter-value-type*/<InputIt>>, class Allocator = allocator</*iter-value-type*/<InputIt>>> multiset(InputIt, InputIt, Compare = Compare(), Allocator = Allocator()) -> multiset</*iter-value-type*/<InputIt>, Compare, Allocator>; template<class Key, class Compare = less<Key>, class Allocator = allocator<Key>> multiset(initializer_list<Key>, Compare = Compare(), Allocator = Allocator()) -> multiset<Key, Compare, Allocator>; template<class InputIt, class Allocator> multiset(InputIt, InputIt, Allocator) -> multiset</*iter-value-type*/<InputIt>, less<iter-value-type<InputIt>>, Allocator>; template<class Key, class Allocator> multiset(initializer_list<Key>, Allocator) -> multiset<Key, less<Key>, Allocator>; // swap template<class Key, class Compare, class Allocator> void swap(multiset<Key, Compare, Allocator>& x, multiset<Key, Compare, Allocator>& y) noexcept(noexcept(x.swap(y))); } ```
programming_docs
cpp Standard library header <ctgmath> (C++11)(until C++20), <tgmath.h> (C++11) Standard library header <ctgmath> (C++11)(until C++20), <tgmath.h> (C++11) ========================================================================== This header was originally in the C standard library as `<tgmath.h>`. This header is part of the [numeric](../numeric "cpp/numeric") library. | | | --- | | Includes | | [<complex>](complex "cpp/header/complex") (C++11) | [Complex number type](../numeric/complex "cpp/numeric/complex") | | [<cmath>](cmath "cpp/header/cmath") (C++11) | [Common mathematics functions](../numeric/math "cpp/numeric/math") | ### Notes `<ctgmath>` is deprecated in C++17 and removed in C++20. Corresponding `<tgmath.h>` is still available in C++20. cpp Standard library header <bit> (C++20) Standard library header <bit> (C++20) ===================================== This header is part of the [numeric](../numeric "cpp/numeric") library. | | | --- | | Types | | [endian](../types/endian "cpp/types/endian") (C++20) | indicates the endianness of scalar types (enum) | | Functions | | [bit\_cast](../numeric/bit_cast "cpp/numeric/bit cast") (C++20) | reinterpret the object representation of one type as that of another (function template) | | [byteswap](../numeric/byteswap "cpp/numeric/byteswap") (C++23) | reverses the bytes in the given integer value (function template) | | [has\_single\_bit](../numeric/has_single_bit "cpp/numeric/has single bit") (C++20) | checks if a number is an integral power of two (function template) | | [bit\_ceil](../numeric/bit_ceil "cpp/numeric/bit ceil") (C++20) | finds the smallest integral power of two not less than the given value (function template) | | [bit\_floor](../numeric/bit_floor "cpp/numeric/bit floor") (C++20) | finds the largest integral power of two not greater than the given value (function template) | | [bit\_width](../numeric/bit_width "cpp/numeric/bit width") (C++20) | finds the smallest number of bits needed to represent the given value (function template) | | [rotl](../numeric/rotl "cpp/numeric/rotl") (C++20) | computes the result of bitwise left-rotation (function template) | | [rotr](../numeric/rotr "cpp/numeric/rotr") (C++20) | computes the result of bitwise right-rotation (function template) | | [countl\_zero](../numeric/countl_zero "cpp/numeric/countl zero") (C++20) | counts the number of consecutive 0 bits, starting from the most significant bit (function template) | | [countl\_one](../numeric/countl_one "cpp/numeric/countl one") (C++20) | counts the number of consecutive 1 bits, starting from the most significant bit (function template) | | [countr\_zero](../numeric/countr_zero "cpp/numeric/countr zero") (C++20) | counts the number of consecutive 0 bits, starting from the least significant bit (function template) | | [countr\_one](../numeric/countr_one "cpp/numeric/countr one") (C++20) | counts the number of consecutive 1 bits, starting from the least significant bit (function template) | | [popcount](../numeric/popcount "cpp/numeric/popcount") (C++20) | counts the number of 1 bits in an unsigned integer (function template) | ### Synopsis ``` namespace std { // bit_cast template<class To, class From> constexpr To bit_cast(const From& from) noexcept; // byteswap template <class T> constexpr T byteswap(T value) noexcept; // integral powers of 2 template<class T> constexpr bool has_single_bit(T x) noexcept; template<class T> constexpr T bit_ceil(T x); template<class T> constexpr T bit_floor(T x) noexcept; template<class T> constexpr int bit_width(T x) noexcept; // rotating template<class T> [[nodiscard]] constexpr T rotl(T x, int s) noexcept; template<class T> [[nodiscard]] constexpr T rotr(T x, int s) noexcept; // counting template<class T> constexpr int countl_zero(T x) noexcept; template<class T> constexpr int countl_one(T x) noexcept; template<class T> constexpr int countr_zero(T x) noexcept; template<class T> constexpr int countr_one(T x) noexcept; template<class T> constexpr int popcount(T x) noexcept; // endian enum class endian { little = /* see description */, big = /* see description */, native = /* see description */ }; } ``` cpp Standard library header <cstdalign> (C++11)(until C++20), <stdalign.h> (C++11) Standard library header <cstdalign> (C++11)(until C++20), <stdalign.h> (C++11) ============================================================================== This header was originally in the C standard library as `<stdalign.h>`. C compatibility header. | | | --- | | Macros | | \_\_alignas\_is\_defined (C++11) | C compatibility macro constant, expands to integer literal `1` (macro constant) | ### Notes `<cstdalign>` is deprecated in C++17 and removed in C++20. Corresponding `<stdalign.h>` is still available in C++20. cpp Standard library header <cmath> Standard library header <cmath> =============================== This header was originally in the C standard library as `<math.h>`. This header is part of the [numeric](../numeric "cpp/numeric") library. | | | --- | | Types | | float\_t (C++11) | most efficient floating-point type at least as wide as `float` (typedef) | | double\_t (C++11) | most efficient floating-point type at least as wide as `double` (typedef) | | Macros | | [HUGE\_VALFHUGE\_VALHUGE\_VALL](../numeric/math/huge_val "cpp/numeric/math/HUGE VAL") (C++11)(C++11) | indicates the overflow value for `float`, `double` and `long double` respectively (macro constant) | | [INFINITY](../numeric/math/infinity "cpp/numeric/math/INFINITY") (C++11) | evaluates to positive infinity or the value guaranteed to overflow a `float` (macro constant) | | [NAN](../numeric/math/nan "cpp/numeric/math/NAN") (C++11) | evaluates to a quiet NaN of type `float` (macro constant) | | [math\_errhandlingMATH\_ERRNOMATH\_ERREXCEPT](../numeric/math/math_errhandling "cpp/numeric/math/math errhandling") (C++11)(C++11)(C++11) | defines the error handling mechanism used by the common mathematical functions (macro constant) | | Classification | | [FP\_NORMALFP\_SUBNORMALFP\_ZEROFP\_INFINITEFP\_NAN](../numeric/math/fp_categories "cpp/numeric/math/FP categories") (C++11)(C++11)(C++11)(C++11)(C++11) | indicates a floating-point category (macro constant) | | Functions | | Basic operations | | [abs(float)fabsfabsffabsl](../numeric/math/fabs "cpp/numeric/math/fabs") (C++11)(C++11) | absolute value of a floating point value (\(\small{|x|}\)|x|) (function) | | [fmodfmodffmodl](../numeric/math/fmod "cpp/numeric/math/fmod") (C++11)(C++11) | remainder of the floating point division operation (function) | | [remainderremainderfremainderl](../numeric/math/remainder "cpp/numeric/math/remainder") (C++11)(C++11)(C++11) | signed remainder of the division operation (function) | | [remquoremquofremquol](../numeric/math/remquo "cpp/numeric/math/remquo") (C++11)(C++11)(C++11) | signed remainder as well as the three last bits of the division operation (function) | | [fmafmaffmal](../numeric/math/fma "cpp/numeric/math/fma") (C++11)(C++11)(C++11) | fused multiply-add operation (function) | | [fmaxfmaxffmaxl](../numeric/math/fmax "cpp/numeric/math/fmax") (C++11)(C++11)(C++11) | larger of two floating-point values (function) | | [fminfminffminl](../numeric/math/fmin "cpp/numeric/math/fmin") (C++11)(C++11)(C++11) | smaller of two floating point values (function) | | [fdimfdimffdiml](../numeric/math/fdim "cpp/numeric/math/fdim") (C++11)(C++11)(C++11) | positive difference of two floating point values (\({\small\max{(0, x-y)} }\)max(0, x-y)) (function) | | [nannanfnanl](../numeric/math/nan "cpp/numeric/math/nan") (C++11)(C++11)(C++11) | not-a-number (NaN) (function) | | Linear interpolation | | [lerp](../numeric/lerp "cpp/numeric/lerp") (C++20) | linear interpolation function (function) | | Exponential functions | | [expexpfexpl](../numeric/math/exp "cpp/numeric/math/exp") (C++11)(C++11) | returns *e* raised to the given power (\({\small e^x}\)ex) (function) | | [exp2exp2fexp2l](../numeric/math/exp2 "cpp/numeric/math/exp2") (C++11)(C++11)(C++11) | returns *2* raised to the given power (\({\small 2^x}\)2x) (function) | | [expm1expm1fexpm1l](../numeric/math/expm1 "cpp/numeric/math/expm1") (C++11)(C++11)(C++11) | returns *e* raised to the given power, minus one (\({\small e^x-1}\)ex-1) (function) | | [loglogflogl](../numeric/math/log "cpp/numeric/math/log") (C++11)(C++11) | computes natural (base *e*) logarithm (\({\small \ln{x} }\)ln(x)) (function) | | [log10log10flog10l](../numeric/math/log10 "cpp/numeric/math/log10") (C++11)(C++11) | computes common (base *10*) logarithm (\({\small \log\_{10}{x} }\)log10(x)) (function) | | [log2log2flog2l](../numeric/math/log2 "cpp/numeric/math/log2") (C++11)(C++11)(C++11) | base 2 logarithm of the given number (\({\small \log\_{2}{x} }\)log2(x)) (function) | | [log1plog1pflog1pl](../numeric/math/log1p "cpp/numeric/math/log1p") (C++11)(C++11)(C++11) | natural logarithm (to base *e*) of 1 plus the given number (\({\small \ln{(1+x)} }\)ln(1+x)) (function) | | Power functions | | [powpowfpowl](../numeric/math/pow "cpp/numeric/math/pow") (C++11)(C++11) | raises a number to the given power (\(\small{x^y}\)xy) (function) | | [sqrtsqrtfsqrtl](../numeric/math/sqrt "cpp/numeric/math/sqrt") (C++11)(C++11) | computes square root (\(\small{\sqrt{x} }\)√x) (function) | | [cbrtcbrtfcbrtl](../numeric/math/cbrt "cpp/numeric/math/cbrt") (C++11)(C++11)(C++11) | computes cubic root (\(\small{\sqrt[3]{x} }\)3√x) (function) | | [hypothypotfhypotl](../numeric/math/hypot "cpp/numeric/math/hypot") (C++11)(C++11)(C++11) | computes square root of the sum of the squares of two or three (C++17) given numbers (\(\scriptsize{\sqrt{x^2+y^2} }\)√x2+y2), (\(\scriptsize{\sqrt{x^2+y^2+z^2} }\)√x2+y2+z2) (function) | | Trigonometric functions | | [sinsinfsinl](../numeric/math/sin "cpp/numeric/math/sin") (C++11)(C++11) | computes sine (\({\small\sin{x} }\)sin(x)) (function) | | [coscosfcosl](../numeric/math/cos "cpp/numeric/math/cos") (C++11)(C++11) | computes cosine (\({\small\cos{x} }\)cos(x)) (function) | | [tantanftanl](../numeric/math/tan "cpp/numeric/math/tan") (C++11)(C++11) | computes tangent (\({\small\tan{x} }\)tan(x)) (function) | | [asinasinfasinl](../numeric/math/asin "cpp/numeric/math/asin") (C++11)(C++11) | computes arc sine (\({\small\arcsin{x} }\)arcsin(x)) (function) | | [acosacosfacosl](../numeric/math/acos "cpp/numeric/math/acos") (C++11)(C++11) | computes arc cosine (\({\small\arccos{x} }\)arccos(x)) (function) | | [atanatanfatanl](../numeric/math/atan "cpp/numeric/math/atan") (C++11)(C++11) | computes arc tangent (\({\small\arctan{x} }\)arctan(x)) (function) | | [atan2atan2fatan2l](../numeric/math/atan2 "cpp/numeric/math/atan2") (C++11)(C++11) | arc tangent, using signs to determine quadrants (function) | | Hyperbolic functions | | [sinhsinhfsinhl](../numeric/math/sinh "cpp/numeric/math/sinh") (C++11)(C++11) | computes hyperbolic sine (\({\small\sinh{x} }\)sinh(x)) (function) | | [coshcoshfcoshl](../numeric/math/cosh "cpp/numeric/math/cosh") (C++11)(C++11) | computes hyperbolic cosine (\({\small\cosh{x} }\)cosh(x)) (function) | | [tanhtanhftanhl](../numeric/math/tanh "cpp/numeric/math/tanh") (C++11)(C++11) | computes hyperbolic tangent (\({\small\tanh{x} }\)tanh(x)) (function) | | [asinhasinhfasinhl](../numeric/math/asinh "cpp/numeric/math/asinh") (C++11)(C++11)(C++11) | computes the inverse hyperbolic sine (\({\small\operatorname{arsinh}{x} }\)arsinh(x)) (function) | | [acoshacoshfacoshl](../numeric/math/acosh "cpp/numeric/math/acosh") (C++11)(C++11)(C++11) | computes the inverse hyperbolic cosine (\({\small\operatorname{arcosh}{x} }\)arcosh(x)) (function) | | [atanhatanhfatanhl](../numeric/math/atanh "cpp/numeric/math/atanh") (C++11)(C++11)(C++11) | computes the inverse hyperbolic tangent (\({\small\operatorname{artanh}{x} }\)artanh(x)) (function) | | Error and gamma functions | | [erferfferfl](../numeric/math/erf "cpp/numeric/math/erf") (C++11)(C++11)(C++11) | error function (function) | | [erfcerfcferfcl](../numeric/math/erfc "cpp/numeric/math/erfc") (C++11)(C++11)(C++11) | complementary error function (function) | | [tgammatgammaftgammal](../numeric/math/tgamma "cpp/numeric/math/tgamma") (C++11)(C++11)(C++11) | gamma function (function) | | [lgammalgammaflgammal](../numeric/math/lgamma "cpp/numeric/math/lgamma") (C++11)(C++11)(C++11) | natural logarithm of the gamma function (function) | | Nearest integer floating-point operations | | [ceilceilfceill](../numeric/math/ceil "cpp/numeric/math/ceil") (C++11)(C++11) | nearest integer not less than the given value (function) | | [floorfloorffloorl](../numeric/math/floor "cpp/numeric/math/floor") (C++11)(C++11) | nearest integer not greater than the given value (function) | | [trunctruncftruncl](../numeric/math/trunc "cpp/numeric/math/trunc") (C++11)(C++11)(C++11) | nearest integer not greater in magnitude than the given value (function) | | [roundroundfroundllroundlroundflroundlllroundllroundfllroundl](../numeric/math/round "cpp/numeric/math/round") (C++11)(C++11)(C++11)(C++11)(C++11)(C++11)(C++11)(C++11)(C++11) | nearest integer, rounding away from zero in halfway cases (function) | | [nearbyintnearbyintfnearbyintl](../numeric/math/nearbyint "cpp/numeric/math/nearbyint") (C++11)(C++11)(C++11) | nearest integer using current rounding mode (function) | | [rintrintfrintllrintlrintflrintlllrintllrintfllrintl](../numeric/math/rint "cpp/numeric/math/rint") (C++11)(C++11)(C++11)(C++11)(C++11)(C++11)(C++11)(C++11)(C++11) | nearest integer using current rounding mode with exception if the result differs (function) | | Floating-point manipulation functions | | [frexpfrexpffrexpl](../numeric/math/frexp "cpp/numeric/math/frexp") (C++11)(C++11) | decomposes a number into significand and a power of `2` (function) | | [ldexpldexpfldexpl](../numeric/math/ldexp "cpp/numeric/math/ldexp") (C++11)(C++11) | multiplies a number by `2` raised to a power (function) | | [modfmodffmodfl](../numeric/math/modf "cpp/numeric/math/modf") (C++11)(C++11) | decomposes a number into integer and fractional parts (function) | | [scalbnscalbnfscalbnlscalblnscalblnfscalblnl](../numeric/math/scalbn "cpp/numeric/math/scalbn") (C++11)(C++11)(C++11)(C++11)(C++11)(C++11) | multiplies a number by `[FLT\_RADIX](../types/climits "cpp/types/climits")` raised to a power (function) | | [ilogbilogbfilogbl](../numeric/math/ilogb "cpp/numeric/math/ilogb") (C++11)(C++11)(C++11) | extracts exponent of the number (function) | | [logblogbflogbl](../numeric/math/logb "cpp/numeric/math/logb") (C++11)(C++11)(C++11) | extracts exponent of the number (function) | | [nextafternextafterfnextafterlnexttowardnexttowardfnexttowardl](../numeric/math/nextafter "cpp/numeric/math/nextafter") (C++11)(C++11) (C++11)(C++11)(C++11)(C++11) | next representable floating point value towards the given value (function) | | [copysigncopysignfcopysignl](../numeric/math/copysign "cpp/numeric/math/copysign") (C++11)(C++11)(C++11) | copies the sign of a floating point value (function) | | Classification and comparison | | [fpclassify](../numeric/math/fpclassify "cpp/numeric/math/fpclassify") (C++11) | categorizes the given floating-point value (function) | | [isfinite](../numeric/math/isfinite "cpp/numeric/math/isfinite") (C++11) | checks if the given number has finite value (function) | | [isinf](../numeric/math/isinf "cpp/numeric/math/isinf") (C++11) | checks if the given number is infinite (function) | | [isnan](../numeric/math/isnan "cpp/numeric/math/isnan") (C++11) | checks if the given number is NaN (function) | | [isnormal](../numeric/math/isnormal "cpp/numeric/math/isnormal") (C++11) | checks if the given number is normal (function) | | [signbit](../numeric/math/signbit "cpp/numeric/math/signbit") (C++11) | checks if the given number is negative (function) | | [isgreater](../numeric/math/isgreater "cpp/numeric/math/isgreater") (C++11) | checks if the first floating-point argument is greater than the second (function) | | [isgreaterequal](../numeric/math/isgreaterequal "cpp/numeric/math/isgreaterequal") (C++11) | checks if the first floating-point argument is greater or equal than the second (function) | | [isless](../numeric/math/isless "cpp/numeric/math/isless") (C++11) | checks if the first floating-point argument is less than the second (function) | | [islessequal](../numeric/math/islessequal "cpp/numeric/math/islessequal") (C++11) | checks if the first floating-point argument is less or equal than the second (function) | | [islessgreater](../numeric/math/islessgreater "cpp/numeric/math/islessgreater") (C++11) | checks if the first floating-point argument is less or greater than the second (function) | | [isunordered](../numeric/math/isunordered "cpp/numeric/math/isunordered") (C++11) | checks if two floating-point values are unordered (function) | | Mathematical special functions | | [assoc\_laguerreassoc\_laguerrefassoc\_laguerrel](../numeric/special_functions/assoc_laguerre "cpp/numeric/special functions/assoc laguerre") (C++17)(C++17)(C++17) | associated Laguerre polynomials (function) | | [assoc\_legendreassoc\_legendrefassoc\_legendrel](../numeric/special_functions/assoc_legendre "cpp/numeric/special functions/assoc legendre") (C++17)(C++17)(C++17) | associated Legendre polynomials (function) | | [betabetafbetal](../numeric/special_functions/beta "cpp/numeric/special functions/beta") (C++17)(C++17)(C++17) | beta function (function) | | [comp\_ellint\_1comp\_ellint\_1fcomp\_ellint\_1l](../numeric/special_functions/comp_ellint_1 "cpp/numeric/special functions/comp ellint 1") (C++17)(C++17)(C++17) | (complete) elliptic integral of the first kind (function) | | [comp\_ellint\_2comp\_ellint\_2fcomp\_ellint\_2l](../numeric/special_functions/comp_ellint_2 "cpp/numeric/special functions/comp ellint 2") (C++17)(C++17)(C++17) | (complete) elliptic integral of the second kind (function) | | [comp\_ellint\_3comp\_ellint\_3fcomp\_ellint\_3l](../numeric/special_functions/comp_ellint_3 "cpp/numeric/special functions/comp ellint 3") (C++17)(C++17)(C++17) | (complete) elliptic integral of the third kind (function) | | [cyl\_bessel\_icyl\_bessel\_ifcyl\_bessel\_il](../numeric/special_functions/cyl_bessel_i "cpp/numeric/special functions/cyl bessel i") (C++17)(C++17)(C++17) | regular modified cylindrical Bessel functions (function) | | [cyl\_bessel\_jcyl\_bessel\_jfcyl\_bessel\_jl](../numeric/special_functions/cyl_bessel_j "cpp/numeric/special functions/cyl bessel j") (C++17)(C++17)(C++17) | cylindrical Bessel functions (of the first kind) (function) | | [cyl\_bessel\_kcyl\_bessel\_kfcyl\_bessel\_kl](../numeric/special_functions/cyl_bessel_k "cpp/numeric/special functions/cyl bessel k") (C++17)(C++17)(C++17) | irregular modified cylindrical Bessel functions (function) | | [cyl\_neumanncyl\_neumannfcyl\_neumannl](../numeric/special_functions/cyl_neumann "cpp/numeric/special functions/cyl neumann") (C++17)(C++17)(C++17) | cylindrical Neumann functions (function) | | [ellint\_1ellint\_1fellint\_1l](../numeric/special_functions/ellint_1 "cpp/numeric/special functions/ellint 1") (C++17)(C++17)(C++17) | (incomplete) elliptic integral of the first kind (function) | | [ellint\_2ellint\_2fellint\_2l](../numeric/special_functions/ellint_2 "cpp/numeric/special functions/ellint 2") (C++17)(C++17)(C++17) | (incomplete) elliptic integral of the second kind (function) | | [ellint\_3ellint\_3fellint\_3l](../numeric/special_functions/ellint_3 "cpp/numeric/special functions/ellint 3") (C++17)(C++17)(C++17) | (incomplete) elliptic integral of the third kind (function) | | [expintexpintfexpintl](../numeric/special_functions/expint "cpp/numeric/special functions/expint") (C++17)(C++17)(C++17) | exponential integral (function) | | [hermitehermitefhermitel](../numeric/special_functions/hermite "cpp/numeric/special functions/hermite") (C++17)(C++17)(C++17) | Hermite polynomials (function) | | [legendrelegendreflegendrel](../numeric/special_functions/legendre "cpp/numeric/special functions/legendre") (C++17)(C++17)(C++17) | Legendre polynomials (function) | | [laguerrelaguerreflaguerrel](../numeric/special_functions/laguerre "cpp/numeric/special functions/laguerre") (C++17)(C++17)(C++17) | Laguerre polynomials (function) | | [riemann\_zetariemann\_zetafriemann\_zetal](../numeric/special_functions/riemann_zeta "cpp/numeric/special functions/riemann zeta") (C++17)(C++17)(C++17) | Riemann zeta function (function) | | [sph\_besselsph\_besselfsph\_bessell](../numeric/special_functions/sph_bessel "cpp/numeric/special functions/sph bessel") (C++17)(C++17)(C++17) | spherical Bessel functions (of the first kind) (function) | | [sph\_legendresph\_legendrefsph\_legendrel](../numeric/special_functions/sph_legendre "cpp/numeric/special functions/sph legendre") (C++17)(C++17)(C++17) | spherical associated Legendre functions (function) | | [sph\_neumannsph\_neumannfsph\_neumannl](../numeric/special_functions/sph_neumann "cpp/numeric/special functions/sph neumann") (C++17)(C++17)(C++17) | spherical Neumann functions (function) | ### Synopsis ``` namespace std { using float_t = /* see description */; using double_t = /* see description */; } #define HUGE_VAL /* see description */ #define HUGE_VALF /* see description */ #define HUGE_VALL /* see description */ #define INFINITY /* see description */ #define NAN /* see description */ #define FP_INFINITE /* see description */ #define FP_NAN /* see description */ #define FP_NORMAL /* see description */ #define FP_SUBNORMAL /* see description */ #define FP_ZERO /* see description */ #define FP_FAST_FMA /* see description */ #define FP_FAST_FMAF /* see description */ #define FP_FAST_FMAL /* see description */ #define FP_ILOGB0 /* see description */ #define FP_ILOGBNAN /* see description */ #define MATH_ERRNO /* see description */ #define MATH_ERREXCEPT /* see description */ #define math_errhandling /* see description */ namespace std { float acos(float x); double acos(double x); long double acos(long double x); float acosf(float x); long double acosl(long double x); float asin(float x); double asin(double x); long double asin(long double x); float asinf(float x); long double asinl(long double x); float atan(float x); double atan(double x); long double atan(long double x); float atanf(float x); long double atanl(long double x); float atan2(float y, float x); double atan2(double y, double x); long double atan2(long double y, long double x); float atan2f(float y, float x); long double atan2l(long double y, long double x); float cos(float x); double cos(double x); long double cos(long double x); float cosf(float x); long double cosl(long double x); float sin(float x); double sin(double x); long double sin(long double x); float sinf(float x); long double sinl(long double x); float tan(float x); double tan(double x); long double tan(long double x); float tanf(float x); long double tanl(long double x); float acosh(float x); double acosh(double x); long double acosh(long double x); float acoshf(float x); long double acoshl(long double x); float asinh(float x); double asinh(double x); long double asinh(long double x); float asinhf(float x); long double asinhl(long double x); float atanh(float x); double atanh(double x); long double atanh(long double x); float atanhf(float x); long double atanhl(long double x); float cosh(float x); double cosh(double x); long double cosh(long double x); float coshf(float x); long double coshl(long double x); float sinh(float x); double sinh(double x); long double sinh(long double x); float sinhf(float x); long double sinhl(long double x); float tanh(float x); double tanh(double x); long double tanh(long double x); float tanhf(float x); long double tanhl(long double x); float exp(float x); double exp(double x); long double exp(long double x); float expf(float x); long double expl(long double x); float exp2(float x); double exp2(double x); long double exp2(long double x); float exp2f(float x); long double exp2l(long double x); float expm1(float x); double expm1(double x); long double expm1(long double x); float expm1f(float x); long double expm1l(long double x); constexpr float frexp(float value, int* exp); constexpr double frexp(double value, int* exp); constexpr long double frexp(long double value, int* exp); constexpr float frexpf(float value, int* exp); constexpr long double frexpl(long double value, int* exp); constexpr int ilogb(float x); constexpr int ilogb(double x); constexpr int ilogb(long double x); constexpr int ilogbf(float x); constexpr int ilogbl(long double x); constexpr float ldexp(float x, int exp); constexpr double ldexp(double x, int exp); constexpr long double ldexp(long double x, int exp); constexpr float ldexpf(float x, int exp); constexpr long double ldexpl(long double x, int exp); float log(float x); double log(double x); long double log(long double x); float logf(float x); long double logl(long double x); float log10(float x); double log10(double x); long double log10(long double x); float log10f(float x); long double log10l(long double x); float log1p(float x); double log1p(double x); long double log1p(long double x); float log1pf(float x); long double log1pl(long double x); float log2(float x); double log2(double x); long double log2(long double x); float log2f(float x); long double log2l(long double x); constexpr float logb(float x); constexpr double logb(double x); constexpr long double logb(long double x); constexpr float logbf(float x); constexpr long double logbl(long double x); constexpr float modf(float value, float* iptr); constexpr double modf(double value, double* iptr); constexpr long double modf(long double value, long double* iptr); constexpr float modff(float value, float* iptr); constexpr long double modfl(long double value, long double* iptr); constexpr float scalbn(float x, int n); constexpr double scalbn(double x, int n); constexpr long double scalbn(long double x, int n); constexpr float scalbnf(float x, int n); constexpr long double scalbnl(long double x, int n); constexpr float scalbln(float x, long int n); constexpr double scalbln(double x, long int n); constexpr long double scalbln(long double x, long int n); constexpr float scalblnf(float x, long int n); constexpr long double scalblnl(long double x, long int n); float cbrt(float x); double cbrt(double x); long double cbrt(long double x); float cbrtf(float x); long double cbrtl(long double x); // absolute values constexpr int abs(int j); constexpr long int abs(long int j); constexpr long long int abs(long long int j); constexpr float abs(float j); constexpr double abs(double j); constexpr long double abs(long double j); constexpr float fabs(float x); constexpr double fabs(double x); constexpr long double fabs(long double x); constexpr float fabsf(float x); constexpr long double fabsl(long double x); float hypot(float x, float y); double hypot(double x, double y); long double hypot(long double x, long double y); float hypotf(float x, float y); long double hypotl(long double x, long double y); // three-dimensional hypotenuse float hypot(float x, float y, float z); double hypot(double x, double y, double z); long double hypot(long double x, long double y, long double z); float pow(float x, float y); double pow(double x, double y); long double pow(long double x, long double y); float powf(float x, float y); long double powl(long double x, long double y); float sqrt(float x); double sqrt(double x); long double sqrt(long double x); float sqrtf(float x); long double sqrtl(long double x); float erf(float x); double erf(double x); long double erf(long double x); float erff(float x); long double erfl(long double x); float erfc(float x); double erfc(double x); long double erfc(long double x); float erfcf(float x); long double erfcl(long double x); float lgamma(float x); double lgamma(double x); long double lgamma(long double x); float lgammaf(float x); long double lgammal(long double x); float tgamma(float x); double tgamma(double x); long double tgamma(long double x); float tgammaf(float x); long double tgammal(long double x); constexpr float ceil(float x); constexpr double ceil(double x); constexpr long double ceil(long double x); constexpr float ceilf(float x); constexpr long double ceill(long double x); constexpr float floor(float x); constexpr double floor(double x); constexpr long double floor(long double x); constexpr float floorf(float x); constexpr long double floorl(long double x); float nearbyint(float x); double nearbyint(double x); long double nearbyint(long double x); float nearbyintf(float x); long double nearbyintl(long double x); float rint(float x); double rint(double x); long double rint(long double x); float rintf(float x); long double rintl(long double x); long int lrint(float x); long int lrint(double x); long int lrint(long double x); long int lrintf(float x); long int lrintl(long double x); long long int llrint(float x); long long int llrint(double x); long long int llrint(long double x); long long int llrintf(float x); long long int llrintl(long double x); constexpr float round(float x); constexpr double round(double x); constexpr long double round(long double x); constexpr float roundf(float x); constexpr long double roundl(long double x); constexpr long int lround(float x); constexpr long int lround(double x); constexpr long int lround(long double x); constexpr long int lroundf(float x); constexpr long int lroundl(long double x); constexpr long long int llround(float x); constexpr long long int llround(double x); constexpr long long int llround(long double x); constexpr long long int llroundf(float x); constexpr long long int llroundl(long double x); constexpr float trunc(float x); constexpr double trunc(double x); constexpr long double trunc(long double x); constexpr float truncf(float x); constexpr long double truncl(long double x); constexpr float fmod(float x, float y); constexpr double fmod(double x, double y); constexpr long double fmod(long double x, long double y); constexpr float fmodf(float x, float y); constexpr long double fmodl(long double x, long double y); constexpr float remainder(float x, float y); constexpr double remainder(double x, double y); constexpr long double remainder(long double x, long double y); constexpr float remainderf(float x, float y); constexpr long double remainderl(long double x, long double y); constexpr float remquo(float x, float y, int* quo); constexpr double remquo(double x, double y, int* quo); constexpr long double remquo(long double x, long double y, int* quo); constexpr float remquof(float x, float y, int* quo); constexpr long double remquol(long double x, long double y, int* quo); constexpr float copysign(float x, float y); constexpr double copysign(double x, double y); constexpr long double copysign(long double x, long double y); constexpr float copysignf(float x, float y); constexpr long double copysignl(long double x, long double y); double nan(const char* tagp); float nanf(const char* tagp); long double nanl(const char* tagp); constexpr float nextafter(float x, float y); constexpr double nextafter(double x, double y); constexpr long double nextafter(long double x, long double y); constexpr float nextafterf(float x, float y); constexpr long double nextafterl(long double x, long double y); constexpr float nexttoward(float x, long double y); constexpr double nexttoward(double x, long double y); constexpr long double nexttoward(long double x, long double y); constexpr float nexttowardf(float x, long double y); constexpr long double nexttowardl(long double x, long double y); constexpr float fdim(float x, float y); constexpr double fdim(double x, double y); constexpr long double fdim(long double x, long double y); constexpr float fdimf(float x, float y); constexpr long double fdiml(long double x, long double y); constexpr float fmax(float x, float y); constexpr double fmax(double x, double y); constexpr long double fmax(long double x, long double y); constexpr float fmaxf(float x, float y); constexpr long double fmaxl(long double x, long double y); constexpr float fmin(float x, float y); constexpr double fmin(double x, double y); constexpr long double fmin(long double x, long double y); constexpr float fminf(float x, float y); constexpr long double fminl(long double x, long double y); constexpr float fma(float x, float y, float z); constexpr double fma(double x, double y, double z); constexpr long double fma(long double x, long double y, long double z); constexpr float fmaf(float x, float y, float z); constexpr long double fmal(long double x, long double y, long double z); // linear interpolation constexpr float lerp(float a, float b, float t) noexcept; constexpr double lerp(double a, double b, double t) noexcept; constexpr long double lerp(long double a, long double b, long double t) noexcept; // classification / comparison functions constexpr int fpclassify(float x); constexpr int fpclassify(double x); constexpr int fpclassify(long double x); constexpr bool isfinite(float x); constexpr bool isfinite(double x); constexpr bool isfinite(long double x); constexpr bool isinf(float x); constexpr bool isinf(double x); constexpr bool isinf(long double x); constexpr bool isnan(float x); constexpr bool isnan(double x); constexpr bool isnan(long double x); constexpr bool isnormal(float x); constexpr bool isnormal(double x); constexpr bool isnormal(long double x); constexpr bool signbit(float x); constexpr bool signbit(double x); constexpr bool signbit(long double x); constexpr bool isgreater(float x, float y); constexpr bool isgreater(double x, double y); constexpr bool isgreater(long double x, long double y); constexpr bool isgreaterequal(float x, float y); constexpr bool isgreaterequal(double x, double y); constexpr bool isgreaterequal(long double x, long double y); constexpr bool isless(float x, float y); constexpr bool isless(double x, double y); constexpr bool isless(long double x, long double y); constexpr bool islessequal(float x, float y); constexpr bool islessequal(double x, double y); constexpr bool islessequal(long double x, long double y); constexpr bool islessgreater(float x, float y); constexpr bool islessgreater(double x, double y); constexpr bool islessgreater(long double x, long double y); constexpr bool isunordered(float x, float y); constexpr bool isunordered(double x, double y); constexpr bool isunordered(long double x, long double y); // mathematical special functions // associated Laguerre polynomials double assoc_laguerre(unsigned n, unsigned m, double x); float assoc_laguerref(unsigned n, unsigned m, float x); long double assoc_laguerrel(unsigned n, unsigned m, long double x); // associated Legendre functions double assoc_legendre(unsigned l, unsigned m, double x); float assoc_legendref(unsigned l, unsigned m, float x); long double assoc_legendrel(unsigned l, unsigned m, long double x); // beta function double beta(double x, double y); float betaf(float x, float y); long double betal(long double x, long double y); // complete elliptic integral of the first kind double comp_ellint_1(double k); float comp_ellint_1f(float k); long double comp_ellint_1l(long double k); // complete elliptic integral of the second kind double comp_ellint_2(double k); float comp_ellint_2f(float k); long double comp_ellint_2l(long double k); // complete elliptic integral of the third kind double comp_ellint_3(double k, double nu); float comp_ellint_3f(float k, float nu); long double comp_ellint_3l(long double k, long double nu); // regular modified cylindrical Bessel functions double cyl_bessel_i(double nu, double x); float cyl_bessel_if(float nu, float x); long double cyl_bessel_il(long double nu, long double x); // cylindrical Bessel functions of the first kind double cyl_bessel_j(double nu, double x); float cyl_bessel_jf(float nu, float x); long double cyl_bessel_jl(long double nu, long double x); // irregular modified cylindrical Bessel functions double cyl_bessel_k(double nu, double x); float cyl_bessel_kf(float nu, float x); long double cyl_bessel_kl(long double nu, long double x); // cylindrical Neumann functions; // cylindrical Bessel functions of the second kind double cyl_neumann(double nu, double x); float cyl_neumannf(float nu, float x); long double cyl_neumannl(long double nu, long double x); // incomplete elliptic integral of the first kind double ellint_1(double k, double phi); float ellint_1f(float k, float phi); long double ellint_1l(long double k, long double phi); // incomplete elliptic integral of the second kind double ellint_2(double k, double phi); float ellint_2f(float k, float phi); long double ellint_2l(long double k, long double phi); // incomplete elliptic integral of the third kind double ellint_3(double k, double nu, double phi); float ellint_3f(float k, float nu, float phi); long double ellint_3l(long double k, long double nu, long double phi); // exponential integral double expint(double x); float expintf(float x); long double expintl(long double x); // Hermite polynomials double hermite(unsigned n, double x); float hermitef(unsigned n, float x); long double hermitel(unsigned n, long double x); // Laguerre polynomials double laguerre(unsigned n, double x); float laguerref(unsigned n, float x); long double laguerrel(unsigned n, long double x); // Legendre polynomials double legendre(unsigned l, double x); float legendref(unsigned l, float x); long double legendrel(unsigned l, long double x); // Riemann zeta function double riemann_zeta(double x); float riemann_zetaf(float x); long double riemann_zetal(long double x); // spherical Bessel functions of the first kind double sph_bessel(unsigned n, double x); float sph_besself(unsigned n, float x); long double sph_bessell(unsigned n, long double x); // spherical associated Legendre functions double sph_legendre(unsigned l, unsigned m, double theta); float sph_legendref(unsigned l, unsigned m, float theta); long double sph_legendrel(unsigned l, unsigned m, long double theta); // spherical Neumann functions; // spherical Bessel functions of the second kind double sph_neumann(unsigned n, double x); float sph_neumannf(unsigned n, float x); long double sph_neumannl(unsigned n, long double x); } ```
programming_docs
cpp Standard library header <spanstream> (C++23) Standard library header <spanstream> (C++23) ============================================ This header is part of the [Input/Output](../io "cpp/io") library. | | | --- | | Classes | | [basic\_spanbuf](../io/basic_spanbuf "cpp/io/basic spanbuf") (C++23) | implements raw fixed character buffer device (class template) | | [basic\_ispanstream](../io/basic_ispanstream "cpp/io/basic ispanstream") (C++23) | implements fixed character buffer input operations (class template) | | [basic\_ospanstream](../io/basic_ospanstream "cpp/io/basic ospanstream") (C++23) | implements fixed character buffer output operations (class template) | | [basic\_spanstream](../io/basic_spanstream "cpp/io/basic spanstream") (C++23) | implements fixed character buffer input/output operations (class template) | | `spanbuf` (C++23) | `std::basic_spanbuf<char>`(typedef) | | `wspanbuf` (C++23) | `std::basic_spanbuf<wchar_t>`(typedef) | | `ispanstream` (C++23) | `std::basic_ispanstream<char>`(typedef) | | `wispanstream` (C++23) | `std::basic_ispanstream<wchar_t>`(typedef) | | `ospanstream` (C++23) | `std::basic_ospanstream<char>`(typedef) | | `wospanstream` (C++23) | `std::basic_ospanstream<wchar_t>`(typedef) | | `spanstream` (C++23) | `std::basic_spanstream<char>`(typedef) | | `wspanstream` (C++23) | `std::basic_spanstream<wchar_t>`(typedef) | | Functions | | [std::swap(std::basic\_spanbuf)](../io/basic_spanbuf/swap2 "cpp/io/basic spanbuf/swap2") (C++23) | specializes the `[std::swap](../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | | [std::swap(std::basic\_ispanstream)](../io/basic_ispanstream/swap2 "cpp/io/basic ispanstream/swap2") (C++23) | specializes the `[std::swap](../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | | [std::swap(std::basic\_ospanstream)](../io/basic_ospanstream/swap2 "cpp/io/basic ospanstream/swap2") (C++23) | specializes the `[std::swap](../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | | [std::swap(std::basic\_spanstream)](../io/basic_spanstream/swap2 "cpp/io/basic spanstream/swap2") (C++23) | specializes the `[std::swap](../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | ### Synopsis ``` namespace std { template<class CharT, class Traits = char_traits<CharT>> class basic_spanbuf; using spanbuf = basic_spanbuf<char>; using wspanbuf = basic_spanbuf<wchar_t>; template<class CharT, class Traits = char_traits<CharT>> class basic_ispanstream; using ispanstream = basic_ispanstream<char>; using wispanstream = basic_ispanstream<wchar_t>; template<class CharT, class Traits = char_traits<CharT>> class basic_ospanstream; using ospanstream = basic_ospanstream<char>; using wospanstream = basic_ospanstream<wchar_t>; template<class CharT, class Traits = char_traits<CharT>> class basic_spanstream; using spanstream = basic_spanstream<char>; using wspanstream = basic_spanstream<wchar_t>; } ``` #### Class template `std::basic_spanbuf` ``` namespace std { template<class CharT, class Traits = char_traits<CharT>> class basic_spanbuf : public basic_streambuf<CharT, Traits> { public: using char_type = CharT; using int_type = typename Traits::int_type; using pos_type = typename Traits::pos_type; using off_type = typename Traits::off_type; using traits_type = Traits; // constructors basic_spanbuf() : basic_spanbuf(ios_base::in | ios_base::out) {} explicit basic_spanbuf(ios_base::openmode which) : basic_spanbuf(std::span<CharT>(), which) {} explicit basic_spanbuf( std::span<CharT> s, ios_base::openmode which = ios_base::in | ios_base::out); basic_spanbuf(const basic_spanbuf&) = delete; basic_spanbuf(basic_spanbuf&& rhs); // assign and swap basic_spanbuf& operator=(const basic_spanbuf&) = delete; basic_spanbuf& operator=(basic_spanbuf&& rhs); void swap(basic_spanbuf& rhs); // get and set std::span<CharT> span() const noexcept; void span(std::span<CharT> s) noexcept; protected: // overridden virtual functions basic_streambuf<CharT, Traits>* setbuf(CharT*, streamsize) override; pos_type seekoff(off_type off, ios_base::seekdir way, ios_base::openmode which = ios_base::in | ios_base::out) override; pos_type seekpos(pos_type sp, ios_base::openmode which = ios_base::in | ios_base::out) override; private: ios_base::openmode mode; // exposition only std::span<CharT> buf; // exposition only }; template<class CharT, class Traits> void swap(basic_spanbuf<CharT, Traits>& x, basic_spanbuf<CharT, Traits>& y); } ``` #### Class template `std::basic_ispanstream` ``` namespace std { template<class CharT, class Traits = char_traits<CharT>> class basic_ispanstream : public basic_istream<CharT, Traits> { public: using char_type = CharT; using int_type = typename Traits::int_type; using pos_type = typename Traits::pos_type; using off_type = typename Traits::off_type; using traits_type = Traits; // constructors explicit basic_ispanstream( std::span<CharT> s, ios_base::openmode which = ios_base::in); basic_ispanstream(const basic_ispanstream&) = delete; basic_ispanstream(basic_ispanstream&& rhs); template<class ROS> explicit basic_ispanstream(ROS&& s); // assign and swap basic_ispanstream& operator=(const basic_ispanstream&) = delete; basic_ispanstream& operator=(basic_ispanstream&& rhs); void swap(basic_ispanstream& rhs); // members basic_spanbuf<CharT, Traits>* rdbuf() const noexcept; std::span<const CharT> span() const noexcept; void span(std::span<CharT> s) noexcept; template<class ROS> void span(ROS&& s) noexcept; private: basic_spanbuf<CharT, Traits> sb; // exposition only }; template<class CharT, class Traits> void swap(basic_ispanstream<CharT, Traits>& x, basic_ispanstream<CharT, Traits>& y); } ``` #### Class template `std::basic_ospanstream` ``` namespace std { template<class CharT, class Traits = char_traits<CharT>> class basic_ospanstream : public basic_ostream<CharT, Traits> { public: using char_type = CharT; using int_type = typename Traits::int_type; using pos_type = typename Traits::pos_type; using off_type = typename Traits::off_type; using traits_type = Traits; // constructors explicit basic_ospanstream( std::span<CharT> s, ios_base::openmode which = ios_base::out); basic_ospanstream(const basic_ospanstream&) = delete; basic_ospanstream(basic_ospanstream&& rhs); // assign and swap basic_ospanstream& operator=(const basic_ospanstream&) = delete; basic_ospanstream& operator=(basic_ospanstream&& rhs); void swap(basic_ospanstream& rhs); // members basic_spanbuf<CharT, Traits>* rdbuf() const noexcept; std::span<CharT> span() const noexcept; void span(std::span<CharT> s) noexcept; private: basic_spanbuf<CharT, Traits> sb; // exposition only }; template<class CharT, class Traits> void swap(basic_ospanstream<CharT, Traits>& x, basic_ospanstream<CharT, Traits>& y); } ``` #### Class template `std::basic_spanstream` ``` namespace std { template<class CharT, class Traits = char_traits<CharT>> class basic_spanstream : public basic_iostream<CharT, Traits> { public: using char_type = charT; using int_type = typename Traits::int_type; using pos_type = typename Traits::pos_type; using off_type = typename Traits::off_type; using traits_type = Traits; // constructors explicit basic_spanstream( std::span<CharT> s, ios_base::openmode which = ios_base::out | ios_base::in); basic_spanstream(const basic_spanstream&) = delete; basic_spanstream(basic_spanstream&& rhs); // assign and swap basic_spanstream& operator=(const basic_spanstream&) = delete; basic_spanstream& operator=(basic_spanstream&& rhs); void swap(basic_spanstream& rhs); // members basic_spanbuf<CharT, Traits>* rdbuf() const noexcept; std::span<CharT> span() const noexcept; void span(std::span<CharT> s) noexcept; private: basic_spanbuf<CharT, Traits> sb; // exposition only }; template<class CharT, class Traits> void swap(basic_spanstream<CharT, Traits>& x, basic_spanstream<CharT, Traits>& y); } ``` cpp Standard library header <span> (C++20) Standard library header <span> (C++20) ====================================== This header is part of the [containers](../container "cpp/container") library. | | | --- | | Classes | | [span](../container/span "cpp/container/span") (C++20) | a non-owning view over a contiguous sequence of objects (class template) | | Constants | | [dynamic\_extent](../container/span/dynamic_extent "cpp/container/span/dynamic extent") (C++20) | a constant of type `size_t` signifying that the `span` has dynamic extent (constant) | | Functions | | [as\_bytesas\_writable\_bytes](../container/span/as_bytes "cpp/container/span/as bytes") (C++20) | converts a `span` into a view of its underlying bytes (function template) | | Range access | | [begincbegin](../iterator/begin "cpp/iterator/begin") (C++11)(C++14) | returns an iterator to the beginning of a container or array (function template) | | [endcend](../iterator/end "cpp/iterator/end") (C++11)(C++14) | returns an iterator to the end of a container or array (function template) | | [rbegincrbegin](../iterator/rbegin "cpp/iterator/rbegin") (C++14) | returns a reverse iterator to the beginning of a container or array (function template) | | [rendcrend](../iterator/rend "cpp/iterator/rend") (C++14) | returns a reverse end iterator for a container or array (function template) | | [sizessize](../iterator/size "cpp/iterator/size") (C++17)(C++20) | returns the size of a container or array (function template) | | [empty](../iterator/empty "cpp/iterator/empty") (C++17) | checks whether the container is empty (function template) | | [data](../iterator/data "cpp/iterator/data") (C++17) | obtains the pointer to the underlying array (function template) | ### Synopsis ``` namespace std { // constants inline constexpr size_t dynamic_extent = numeric_limits<size_t>::max(); // class template span template<class ElementType, size_t Extent = dynamic_extent> class span; template<class ElementType, size_t Extent> inline constexpr bool ranges::enable_borrowed_range<span<ElementType, Extent>> = true; // views of object representation template<class ElementType, size_t Extent> span<const byte, Extent == dynamic_extent ? dynamic_extent : sizeof(ElementType) * Extent> as_bytes(span<ElementType, Extent> s) noexcept; template<class ElementType, size_t Extent> span<byte, Extent == dynamic_extent ? dynamic_extent : sizeof(ElementType) * Extent> as_writable_bytes(span<ElementType, Extent> s) noexcept; } ``` #### Class template `std::span` ``` namespace std { template<class ElementType, size_t Extent = dynamic_extent> class span { public: // constants and types using element_type = ElementType; using value_type = remove_cv_t<ElementType>; using size_type = size_t; using difference_type = ptrdiff_t; using pointer = element_type*; using const_pointer = const element_type*; using reference = element_type&; using const_reference = const element_type&; using iterator = /* implementation-defined */; using const_iterator = std::const_iterator<iterator>; using reverse_iterator = std::reverse_iterator<iterator>; using const_reverse_iterator = std::const_iterator<reverse_iterator>; static constexpr size_type extent = Extent; // constructors, copy, and assignment constexpr span() noexcept; template<class It> constexpr explicit(extent != dynamic_extent) span(It first, size_type count); template<class It, class End> constexpr explicit(extent != dynamic_extent) span(It first, End last); template<size_t N> constexpr span(type_identity_t<element_type> (&arr)[N]) noexcept; template<class T, size_t N> constexpr span(array<T, N>& arr) noexcept; template<class T, size_t N> constexpr span(const array<T, N>& arr) noexcept; template<class R> constexpr explicit(extent != dynamic_extent) span(R&& r); constexpr span(const span& other) noexcept = default; template<class OtherElementType, size_t OtherExtent> constexpr explicit(/* see description */) span(const span<OtherElementType, OtherExtent>& s) noexcept; ~span() noexcept = default; constexpr span& operator=(const span& other) noexcept = default; // subviews template<size_t Count> constexpr span<element_type, Count> first() const; template<size_t Count> constexpr span<element_type, Count> last() const; template<size_t Offset, size_t Count = dynamic_extent> constexpr span<element_type, /* see description */> subspan() const; constexpr span<element_type, dynamic_extent> first(size_type count) const; constexpr span<element_type, dynamic_extent> last(size_type count) const; constexpr span<element_type, dynamic_extent> subspan( size_type offset, size_type count = dynamic_extent) const; // observers constexpr size_type size() const noexcept; constexpr size_type size_bytes() const noexcept; [[nodiscard]] constexpr bool empty() const noexcept; // element access constexpr reference operator[](size_type idx) const; constexpr reference front() const; constexpr reference back() const; constexpr pointer data() const noexcept; // iterator support constexpr iterator begin() const noexcept; constexpr iterator end() const noexcept; constexpr const_iterator cbegin() const noexcept; constexpr const_iterator cend() const noexcept; constexpr reverse_iterator rbegin() const noexcept; constexpr reverse_iterator rend() const noexcept; constexpr const_reverse_iterator crbegin() const noexcept; constexpr const_reverse_iterator crend() const noexcept; private: pointer data_; // exposition only size_type size_; // exposition only }; template<class It, class EndOrSize> span(It, EndOrSize) -> span<remove_reference_t<iter_reference_t<It>>>; template<class T, size_t N> span(T (&)[N]) -> span<T, N>; template<class T, size_t N> span(array<T, N>&) -> span<T, N>; template<class T, size_t N> span(const array<T, N>&) -> span<const T, N>; template<class R> span(R&&) -> span<remove_reference_t<ranges::range_reference_t<R>>>; } ``` cpp Standard library header <streambuf> Standard library header <streambuf> =================================== This header is part of the [Input/Output](../io "cpp/io") library. | | | --- | | Classes | | [basic\_streambuf](../io/basic_streambuf "cpp/io/basic streambuf") | abstracts a raw device (class template) | | `streambuf` | `[std::basic\_streambuf](http://en.cppreference.com/w/cpp/io/basic_streambuf)<char>`(typedef) | | `wstreambuf` | `[std::basic\_streambuf](http://en.cppreference.com/w/cpp/io/basic_streambuf)<wchar\_t>`(typedef) | ### Synopsis ``` namespace std { template<class CharT, class Traits = char_traits<CharT>> class basic_streambuf; using streambuf = basic_streambuf<char>; using wstreambuf = basic_streambuf<wchar_t>; } ``` #### Class template `[std::basic\_streambuf](../io/basic_streambuf "cpp/io/basic streambuf")` ``` namespace std { template<class CharT, class Traits = char_traits<CharT>> class basic_streambuf { public: using char_type = CharT; using int_type = typename Traits::int_type; using pos_type = typename Traits::pos_type; using off_type = typename Traits::off_type; using traits_type = Traits; virtual ~basic_streambuf(); // locales locale pubimbue(const locale& loc); locale getloc() const; // buffer and positioning basic_streambuf* pubsetbuf(char_type* s, streamsize n); pos_type pubseekoff(off_type off, ios_base::seekdir way, ios_base::openmode which = ios_base::in | ios_base::out); pos_type pubseekpos(pos_type sp, ios_base::openmode which = ios_base::in | ios_base::out); int pubsync(); // get and put areas // get area streamsize in_avail(); int_type snextc(); int_type sbumpc(); int_type sgetc(); streamsize sgetn(char_type* s, streamsize n); // putback int_type sputbackc(char_type c); int_type sungetc(); // put area int_type sputc(char_type c); streamsize sputn(const char_type* s, streamsize n); protected: basic_streambuf(); basic_streambuf(const basic_streambuf& rhs); basic_streambuf& operator=(const basic_streambuf& rhs); void swap(basic_streambuf& rhs); // get area access char_type* eback() const; char_type* gptr() const; char_type* egptr() const; void gbump(int n); void setg(char_type* gbeg, char_type* gnext, char_type* gend); // put area access char_type* pbase() const; char_type* pptr() const; char_type* epptr() const; void pbump(int n); void setp(char_type* pbeg, char_type* pend); // virtual functions // locales virtual void imbue(const locale& loc); // buffer management and positioning virtual basic_streambuf* setbuf(char_type* s, streamsize n); virtual pos_type seekoff(off_type off, ios_base::seekdir way, ios_base::openmode which = ios_base::in | ios_base::out); virtual pos_type seekpos(pos_type sp, ios_base::openmode which = ios_base::in | ios_base::out); virtual int sync(); // get area virtual streamsize showmanyc(); virtual streamsize xsgetn(char_type* s, streamsize n); virtual int_type underflow(); virtual int_type uflow(); // putback virtual int_type pbackfail(int_type c = Traits::eof()); // put area virtual streamsize xsputn(const char_type* s, streamsize n); virtual int_type overflow(int_type c = Traits::eof()); }; } ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 56](https://cplusplus.github.io/LWG/issue56) | C++98 | the return type of `showmanyc` of was `int` in the synopsis | corrected to `streamsize` | cpp Standard library header <version> (C++20) Standard library header <version> (C++20) ========================================= This header is part of the [language support](../utility#Language_support "cpp/utility") library. This header supplies implementation-dependent information about the standard library (such as implementation-specific library version macros). Including **`<version>`** also defines all [library feature-test macros](../feature_test#Library_features "cpp/feature test"). ### Notes Prior to C++20, including [`<ciso646>`](ciso646 "cpp/header/ciso646") is sometimes used for this purpose. ### See also | | | | --- | --- | | [**Library feature-test macros**](../utility/feature_test "cpp/utility/feature test") | defined in the header **`<version>`** (C++20) |
programming_docs
cpp Standard library header <new> Standard library header <new> ============================= This header is part of the [dynamic memory management](../memory "cpp/memory") library, in particular provides [low level memory management](../memory/new "cpp/memory/new") features. | | | --- | | Classes | | [bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc") | exception thrown when memory allocation fails (class) | | [bad\_array\_new\_length](../memory/new/bad_array_new_length "cpp/memory/new/bad array new length") (C++11) | exception thrown on allocation of array with invalid length (class) | | [nothrow\_t](../memory/new/nothrow_t "cpp/memory/new/nothrow t") | tag type used to select an non-throwing *allocation function* (class) | | [align\_val\_t](../memory/new/align_val_t "cpp/memory/new/align val t") (C++17) | type used to pass alignment to alignment-aware allocation and deallocation functions (enum) | | [destroying\_delete\_t](../memory/new/destroying_delete_t "cpp/memory/new/destroying delete t") (C++20) | tag type used to identify destroying-delete overloads of operator delete (class) | | Types | | [new\_handler](../memory/new/new_handler "cpp/memory/new/new handler") | function pointer type of the new handler (typedef) | | Constants | | [nothrow](../memory/new/nothrow "cpp/memory/new/nothrow") | an object of type `nothrow_t` used to select an non-throwing *allocation function* (constant) | | [destroying\_delete](../memory/new/destroying_delete "cpp/memory/new/destroying delete") (C++20) | an object of type destroying\_delete\_t used to select destroying-delete overloads of operator delete (constant) | | [hardware\_destructive\_interference\_sizehardware\_constructive\_interference\_size](../thread/hardware_destructive_interference_size "cpp/thread/hardware destructive interference size") (C++17) | min offset to avoid false sharingmax offset to promote true sharing (constant) | | Functions | | [operator newoperator new[]](../memory/new/operator_new "cpp/memory/new/operator new") | allocation functions (function) | | [operator deleteoperator delete[]](../memory/new/operator_delete "cpp/memory/new/operator delete") | deallocation functions (function) | | [get\_new\_handler](../memory/new/get_new_handler "cpp/memory/new/get new handler") (C++11) | obtains the current new handler (function) | | [set\_new\_handler](../memory/new/set_new_handler "cpp/memory/new/set new handler") | registers a new handler (function) | | [launder](../utility/launder "cpp/utility/launder") (C++17) | pointer optimization barrier (function template) | ### Synopsis ``` namespace std { // storage allocation errors class bad_alloc; class bad_array_new_length; struct destroying_delete_t { explicit destroying_delete_t() = default; }; inline constexpr destroying_delete_t destroying_delete{}; // global operator new control enum class align_val_t : size_t {}; struct nothrow_t { explicit nothrow_t() = default; }; extern const nothrow_t nothrow; using new_handler = void (*)(); new_handler get_new_handler() noexcept; new_handler set_new_handler(new_handler new_p) noexcept; // pointer optimization barrier template<class T> [[nodiscard]] constexpr T* launder(T* p) noexcept; // hardware interference size inline constexpr size_t hardware_destructive_interference_size = /* implementation-defined */; inline constexpr size_t hardware_constructive_interference_size = /* implementation-defined */; } // storage allocation and deallocation [[nodiscard]] void* operator new(std::size_t size); [[nodiscard]] void* operator new(std::size_t size, std::align_val_t alignment); [[nodiscard]] void* operator new(std::size_t size, const std::nothrow_t&) noexcept; [[nodiscard]] void* operator new(std::size_t size, std::align_val_t alignment, const std::nothrow_t&) noexcept; void operator delete(void* ptr) noexcept; void operator delete(void* ptr, std::size_t size) noexcept; void operator delete(void* ptr, std::align_val_t alignment) noexcept; void operator delete(void* ptr, std::size_t size, std::align_val_t alignment) noexcept; void operator delete(void* ptr, const std::nothrow_t&) noexcept; void operator delete(void* ptr, std::align_val_t alignment, const std::nothrow_t&) noexcept; [[nodiscard]] void* operator new[](std::size_t size); [[nodiscard]] void* operator new[](std::size_t size, std::align_val_t alignment); [[nodiscard]] void* operator new[](std::size_t size, const std::nothrow_t&) noexcept; [[nodiscard]] void* operator new[](std::size_t size, std::align_val_t alignment, const std::nothrow_t&) noexcept; void operator delete[](void* ptr) noexcept; void operator delete[](void* ptr, std::size_t size) noexcept; void operator delete[](void* ptr, std::align_val_t alignment) noexcept; void operator delete[](void* ptr, std::size_t size, std::align_val_t alignment) noexcept; void operator delete[](void* ptr, const std::nothrow_t&) noexcept; void operator delete[](void* ptr, std::align_val_t alignment, const std::nothrow_t&) noexcept; [[nodiscard]] void* operator new (std::size_t size, void* ptr) noexcept; [[nodiscard]] void* operator new[](std::size_t size, void* ptr) noexcept; void operator delete (void* ptr, void*) noexcept; void operator delete[](void* ptr, void*) noexcept; ``` cpp Standard library header <complex> Standard library header <complex> ================================= This header is part of the [numeric](../numeric "cpp/numeric") library. ### Classes | | | | --- | --- | | [complex](../numeric/complex "cpp/numeric/complex") | a complex number type (class template) | | [`complex`<float>`complex`<double>`complex`<long double>](../numeric/complex "cpp/numeric/complex") | a complex number type (class template specialization) | ### Functions | | | --- | | Operations | | [operator+operator-](../numeric/complex/operator_arith2 "cpp/numeric/complex/operator arith2") | applies unary operators to complex numbers (function template) | | [operator+operator-operator\*operator/](../numeric/complex/operator_arith3 "cpp/numeric/complex/operator arith3") | performs complex number arithmetics on two complex values or a complex and a scalar (function template) | | [operator==operator!=](../numeric/complex/operator_cmp "cpp/numeric/complex/operator cmp") (removed in C++20) | compares two complex numbers or a complex and a scalar (function template) | | [operator<<operator>>](../numeric/complex/operator_ltltgtgt "cpp/numeric/complex/operator ltltgtgt") | serializes and deserializes a complex number (function template) | | [real](../numeric/complex/real2 "cpp/numeric/complex/real2") | returns the real component (function template) | | [imag](../numeric/complex/imag2 "cpp/numeric/complex/imag2") | returns the imaginary component (function template) | | [abs(std::complex)](../numeric/complex/abs "cpp/numeric/complex/abs") | returns the magnitude of a complex number (function template) | | [arg](../numeric/complex/arg "cpp/numeric/complex/arg") | returns the phase angle (function template) | | [norm](../numeric/complex/norm "cpp/numeric/complex/norm") | returns the squared magnitude (function template) | | [conj](../numeric/complex/conj "cpp/numeric/complex/conj") | returns the complex conjugate (function template) | | [proj](../numeric/complex/proj "cpp/numeric/complex/proj") (C++11) | returns the projection onto the Riemann sphere (function template) | | [polar](../numeric/complex/polar "cpp/numeric/complex/polar") | constructs a complex number from magnitude and phase angle (function template) | | Exponential functions | | [exp(std::complex)](../numeric/complex/exp "cpp/numeric/complex/exp") | complex base *e* exponential (function template) | | [log(std::complex)](../numeric/complex/log "cpp/numeric/complex/log") | complex natural logarithm with the branch cuts along the negative real axis (function template) | | [log10(std::complex)](../numeric/complex/log10 "cpp/numeric/complex/log10") | complex common logarithm with the branch cuts along the negative real axis (function template) | | Power functions | | [pow(std::complex)](../numeric/complex/pow "cpp/numeric/complex/pow") | complex power, one or both arguments may be a complex number (function template) | | [sqrt(std::complex)](../numeric/complex/sqrt "cpp/numeric/complex/sqrt") | complex square root in the range of the right half-plane (function template) | | Trigonometric functions | | [sin(std::complex)](../numeric/complex/sin "cpp/numeric/complex/sin") | computes sine of a complex number (\({\small\sin{z} }\)sin(z)) (function template) | | [cos(std::complex)](../numeric/complex/cos "cpp/numeric/complex/cos") | computes cosine of a complex number (\({\small\cos{z} }\)cos(z)) (function template) | | [tan(std::complex)](../numeric/complex/tan "cpp/numeric/complex/tan") | computes tangent of a complex number (\({\small\tan{z} }\)tan(z)) (function template) | | [asin(std::complex)](../numeric/complex/asin "cpp/numeric/complex/asin") (C++11) | computes arc sine of a complex number (\({\small\arcsin{z} }\)arcsin(z)) (function template) | | [acos(std::complex)](../numeric/complex/acos "cpp/numeric/complex/acos") (C++11) | computes arc cosine of a complex number (\({\small\arccos{z} }\)arccos(z)) (function template) | | [atan(std::complex)](../numeric/complex/atan "cpp/numeric/complex/atan") (C++11) | computes arc tangent of a complex number (\({\small\arctan{z} }\)arctan(z)) (function template) | | Hyperbolic functions | | [sinh(std::complex)](../numeric/complex/sinh "cpp/numeric/complex/sinh") | computes hyperbolic sine of a complex number (\({\small\sinh{z} }\)sinh(z)) (function template) | | [cosh(std::complex)](../numeric/complex/cosh "cpp/numeric/complex/cosh") | computes hyperbolic cosine of a complex number (\({\small\cosh{z} }\)cosh(z)) (function template) | | [tanh(std::complex)](../numeric/complex/tanh "cpp/numeric/complex/tanh") | computes hyperbolic tangent of a complex number (\({\small\tanh{z} }\)tanh(z)) (function template) | | [asinh(std::complex)](../numeric/complex/asinh "cpp/numeric/complex/asinh") (C++11) | computes area hyperbolic sine of a complex number (\({\small\operatorname{arsinh}{z} }\)arsinh(z)) (function template) | | [acosh(std::complex)](../numeric/complex/acosh "cpp/numeric/complex/acosh") (C++11) | computes area hyperbolic cosine of a complex number (\({\small\operatorname{arcosh}{z} }\)arcosh(z)) (function template) | | [atanh(std::complex)](../numeric/complex/atanh "cpp/numeric/complex/atanh") (C++11) | computes area hyperbolic tangent of a complex number (\({\small\operatorname{artanh}{z} }\)artanh(z)) (function template) | | Literals | | [operator""ifoperator""ioperator""il](../numeric/complex/operator%22%22i "cpp/numeric/complex/operator\"\"i") (C++14) | A `[std::complex](../numeric/complex "cpp/numeric/complex")` literal representing pure imaginary number (function) | ### Synopsis ``` namespace std { template<class T> class complex; template<> class complex<float>; template<> class complex<double>; template<> class complex<long double>; // operators: template<class T> constexpr complex<T> operator+( const complex<T>&, const complex<T>&); template<class T> constexpr complex<T> operator+(const complex<T>&, const T&); template<class T> constexpr complex<T> operator+(const T&, const complex<T>&); template<class T> constexpr complex<T> operator-( const complex<T>&, const complex<T>&); template<class T> constexpr complex<T> operator-(const complex<T>&, const T&); template<class T> constexpr complex<T> operator-(const T&, const complex<T>&); template<class T> constexpr complex<T> operator*( const complex<T>&, const complex<T>&); template<class T> constexpr complex<T> operator*(const complex<T>&, const T&); template<class T> constexpr complex<T> operator*(const T&, const complex<T>&); template<class T> constexpr complex<T> operator/( const complex<T>&, const complex<T>&); template<class T> constexpr complex<T> operator/(const complex<T>&, const T&); template<class T> constexpr complex<T> operator/(const T&, const complex<T>&); template<class T> constexpr complex<T> operator+(const complex<T>&); template<class T> constexpr complex<T> operator-(const complex<T>&); template<class T> constexpr bool operator== const complex<T>&, const complex<T>&); template<class T> constexpr bool operator==(const complex<T>&, const T&); template<class T> constexpr bool operator==(const T&, const complex<T>&); template<class T> constexpr bool operator!=(const complex<T>&, const complex<T>&); template<class T> constexpr bool operator!=(const complex<T>&, const T&); template<class T> constexpr bool operator!=(const T&, const complex<T>&); template<class T, class charT, class traits> basic_istream<charT, traits>& operator>>(basic_istream<charT, traits>&, complex<T>&); template<class T, class charT, class traits> basic_ostream<charT, traits>& operator<<(basic_ostream<charT, traits>&, const complex<T>&); // values: template<class T> constexpr T real(const complex<T>&); template<class T> constexpr T imag(const complex<T>&); template<class T> T abs(const complex<T>&); template<class T> T arg(const complex<T>&); template<class T> constexpr T norm(const complex<T>&); template<class T> constexpr complex<T> conj(const complex<T>&); template<class T> complex<T> proj(const complex<T>&); template<class T> complex<T> polar(const T&, const T& = 0); // transcendentals: template<class T> complex<T> acos(const complex<T>&); template<class T> complex<T> asin(const complex<T>&); template<class T> complex<T> atan(const complex<T>&); template<class T> complex<T> acosh(const complex<T>&); template<class T> complex<T> asinh(const complex<T>&); template<class T> complex<T> atanh(const complex<T>&); template<class T> complex<T> cos (const complex<T>&); template<class T> complex<T> cosh (const complex<T>&); template<class T> complex<T> exp (const complex<T>&); template<class T> complex<T> log (const complex<T>&); template<class T> complex<T> log10(const complex<T>&); template<class T> complex<T> pow(const complex<T>&, const T&); template<class T> complex<T> pow(const complex<T>&, const complex<T>&); template<class T> complex<T> pow(const T&, const complex<T>&); template<class T> complex<T> sin (const complex<T>&); template<class T> complex<T> sinh(const complex<T>&); template<class T> complex<T> sqrt(const complex<T>&); template<class T> complex<T> tan (const complex<T>&); template<class T> complex<T> tanh(const complex<T>&); // complex literals: inline namespace literals { inline namespace complex_literals { constexpr complex<long double> operator""il(long double); constexpr complex<long double> operator""il(unsigned long long); constexpr complex<double> operator""i(long double); constexpr complex<double> operator""i(unsigned long long); constexpr complex<float> operator""if(long double); constexpr complex<float> operator""if(unsigned long long); } } } ``` #### Class `[std::complex](../numeric/complex "cpp/numeric/complex")` ``` template<class T> class complex { public: typedef T value_type; constexpr complex(const T& re = T(), const T& im = T()); constexpr complex(const complex&); template<class X> constexpr complex(const complex<X>&); constexpr T real() const; constexpr void real(T); constexpr T imag() const; constexpr void imag(T); constexpr complex<T>& operator= (const T&); constexpr complex<T>& operator+=(const T&); constexpr complex<T>& operator-=(const T&); constexpr complex<T>& operator*=(const T&); constexpr complex<T>& operator/=(const T&); constexpr complex& operator=(const complex&); template<class X> constexpr complex<T>& operator= (const complex<X>&); template<class X> constexpr complex<T>& operator+=(const complex<X>&); template<class X> constexpr complex<T>& operator-=(const complex<X>&); template<class X> constexpr complex<T>& operator*=(const complex<X>&); template<class X> constexpr complex<T>& operator/=(const complex<X>&); }; ``` #### `[std::complex](../numeric/complex "cpp/numeric/complex")` specializations ``` template<> class complex<float> { public: typedef float value_type; constexpr complex(float re = 0.0f, float im = 0.0f); explicit constexpr complex(const complex<double>&); explicit constexpr complex(const complex<long double>&); constexpr float real() const; constexpr void real(float); constexpr float imag() const; constexpr void imag(float); constexpr complex<float>& operator= (float); constexpr complex<float>& operator+=(float); constexpr complex<float>& operator-=(float); constexpr complex<float>& operator*=(float); constexpr complex<float>& operator/=(float); constexpr complex<float>& operator=(const complex<float>&); template<class X> constexpr complex<float>& operator= (const complex<X>&); template<class X> constexpr complex<float>& operator+=(const complex<X>&); template<class X> constexpr complex<float>& operator-=(const complex<X>&); template<class X> constexpr complex<float>& operator*=(const complex<X>&); template<class X> constexpr complex<float>& operator/=(const complex<X>&); }; template<> class complex<double> { public: typedef double value_type; constexpr complex(double re = 0.0, double im = 0.0); constexpr complex(const complex<float>&); explicit constexpr complex(const complex<long double>&); constexpr double real() const; constexpr void real(double); constexpr double imag() const; constexpr void imag(double); constexpr complex<double>& operator= (double); constexpr complex<double>& operator+=(double); constexpr complex<double>& operator-=(double); constexpr complex<double>& operator*=(double); constexpr complex<double>& operator/=(double); constexpr complex<double>& operator=(const complex<double>&); template<class X> constexpr complex<double>& operator= (const complex<X>&); template<class X> constexpr complex<double>& operator+=(const complex<X>&); template<class X> constexpr complex<double>& operator-=(const complex<X>&); template<class X> constexpr complex<double>& operator*=(const complex<X>&); template<class X> constexpr complex<double>& operator/=(const complex<X>&); }; template<> class complex<long double> { public: typedef long double value_type; constexpr complex(long double re = 0.0L, long double im = 0.0L); constexpr complex(const complex<float>&); constexpr complex(const complex<double>&); constexpr long double real() const; constexpr void real(long double); constexpr long double imag() const; constexpr void imag(long double); constexpr complex<long double>& operator= (const complex<long double>&); constexpr complex<long double>& operator= (long double); constexpr complex<long double>& operator+=(long double); constexpr complex<long double>& operator-=(long double); constexpr complex<long double>& operator*=(long double); constexpr complex<long double>& operator/=(long double); template<class X> constexpr complex<long double>& operator= (const complex<X>&); template<class X> constexpr complex<long double>& operator+=(const complex<X>&); template<class X> constexpr complex<long double>& operator-=(const complex<X>&); template<class X> constexpr complex<long double>& operator*=(const complex<X>&); template<class X> constexpr complex<long double>& operator/=(const complex<X>&); }; ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 79](https://cplusplus.github.io/LWG/issue79) | C++98 | the default argument of the second parameterof [`polar`](../numeric/complex/polar "cpp/numeric/complex/polar") was missing in the synopsis | added |
programming_docs
cpp Standard library header <flat_map> (C++23) Standard library header <flat\_map> (C++23) =========================================== This header is part of the [containers](../container "cpp/container") library. | | | --- | | Includes | | [<compare>](compare "cpp/header/compare") (C++20) | [Three-way comparison operator](../language/operator_comparison#Three-way_comparison "cpp/language/operator comparison") support | | [<initializer\_list>](initializer_list "cpp/header/initializer list") (C++11) | `[std::initializer\_list](../utility/initializer_list "cpp/utility/initializer list")` class template | | Classes | | [flat\_map](https://en.cppreference.com/mwiki/index.php?title=cpp/container/flat_map&action=edit&redlink=1 "cpp/container/flat map (page does not exist)") (C++23) | adapts a container to provide a collection of key-value pairs, sorted by keys, keys are unique (class template) | | [flat\_multimap](https://en.cppreference.com/mwiki/index.php?title=cpp/container/flat_multimap&action=edit&redlink=1 "cpp/container/flat multimap (page does not exist)") (C++23) | adapts a container to provide a collection of key-value pairs, sorted by keys (class template) | | [sorted\_unique\_t](https://en.cppreference.com/mwiki/index.php?title=cpp/container/sorted_unique&action=edit&redlink=1 "cpp/container/sorted unique (page does not exist)") (C++23) | a tag type used to indicate that elements of a container or range are sorted and unique (class) | | [sorted\_equivalent\_t](https://en.cppreference.com/mwiki/index.php?title=cpp/container/sorted_equivalent&action=edit&redlink=1 "cpp/container/sorted equivalent (page does not exist)") (C++23) | a tag type used to indicate that elements of a container or range are sorted (uniqueness is not required) (class) | | [std::uses\_allocator<std::flat\_map>](https://en.cppreference.com/mwiki/index.php?title=cpp/container/flat_map/uses_allocator&action=edit&redlink=1 "cpp/container/flat map/uses allocator (page does not exist)") (C++23) | specializes the `[std::uses\_allocator](../memory/uses_allocator "cpp/memory/uses allocator")` type trait (class template specialization) | | [std::uses\_allocator<std::flat\_multimap>](https://en.cppreference.com/mwiki/index.php?title=cpp/container/flat_multimap/uses_allocator&action=edit&redlink=1 "cpp/container/flat multimap/uses allocator (page does not exist)") (C++23) | specializes the `[std::uses\_allocator](../memory/uses_allocator "cpp/memory/uses allocator")` type trait (class template specialization) | | Functions | | [erase\_if(std::flat\_map)](https://en.cppreference.com/mwiki/index.php?title=cpp/container/flat_map/erase_if&action=edit&redlink=1 "cpp/container/flat map/erase if (page does not exist)") (C++23) | Erases all elements satisfying specific criteria (function template) | | [erase\_if(std::flat\_multimap)](https://en.cppreference.com/mwiki/index.php?title=cpp/container/flat_multimap/erase_if&action=edit&redlink=1 "cpp/container/flat multimap/erase if (page does not exist)") (C++23) | Erases all elements satisfying specific criteria (function template) | | Constants | | [sorted\_unique](https://en.cppreference.com/mwiki/index.php?title=cpp/container/sorted_unique&action=edit&redlink=1 "cpp/container/sorted unique (page does not exist)") (C++23) | an object of type `std::sorted_unique_t` (constant) | | [sorted\_equivalent](https://en.cppreference.com/mwiki/index.php?title=cpp/container/sorted_equivalent&action=edit&redlink=1 "cpp/container/sorted equivalent (page does not exist)") (C++23) | an object of type `std::sorted_equivalent_t` (constant) | ### Synopsis ``` #include <compare> #include <initializer_list> namespace std { // class template flat_map template<class Key, class T, class Compare = less<Key>, class KeyContainer = vector<Key>, class MappedContainer = vector<T>> class flat_map; struct sorted_unique_t { explicit sorted_unique_t() = default; }; inline constexpr sorted_unique_t sorted_unique{}; template<class Key, class T, class Compare, class KeyContainer, class MappedContainer, class Predicate> size_t erase_if(flat_map<Key, T, Compare, KeyContainer, MappedContainer>& c, Predicate pred); template<class Key, class T, class Compare, class KeyContainer, class MappedContainer, class Allocator> struct uses_allocator<flat_map<Key, T, Compare, KeyContainer, MappedContainer>, Allocator>; // class template flat_multimap template<class Key, class T, class Compare = less<Key>, class KeyContainer = vector<Key>, class MappedContainer = vector<T>> class flat_multimap; struct sorted_equivalent_t { explicit sorted_equivalent_t() = default; }; inline constexpr sorted_equivalent_t sorted_equivalent{}; template<class Key, class T, class Compare, class KeyContainer, class MappedContainer, class Predicate> size_t erase_if(flat_multimap<Key, T, Compare, KeyContainer, MappedContainer>& c, Predicate pred); template<class Key, class T, class Compare, class KeyContainer, class MappedContainer, class Allocator> struct uses_allocator<flat_multimap<Key, T, Compare, KeyContainer, MappedContainer>, Allocator>; } ``` #### Class template `std::flat_map` ``` namespace std { template<class Key, class T, class Compare = less<Key>, class KeyContainer = vector<Key>, class MappedContainer = vector<T>> class flat_map { public: // types using key_type = Key; using mapped_type = T; using value_type = pair<key_type, mapped_type>; using key_compare = Compare; using reference = pair<const key_type&, mapped_type&>; using const_reference = pair<const key_type&, const mapped_type&>; using size_type = size_t; using difference_type = ptrdiff_t; using iterator = /* implementation-defined */; using const_iterator = /* implementation-defined */; using reverse_iterator = std::reverse_iterator<iterator>; using const_reverse_iterator = std::reverse_iterator<const_iterator>; using key_container_type = KeyContainer; using mapped_container_type = MappedContainer; class value_compare { private: key_compare comp; // exposition only value_compare(key_compare c) : comp(c) { } // exposition only public: bool operator()(const_reference x, const_reference y) const { return comp(x.first, y.first); } }; struct containers { key_container_type keys; mapped_container_type values; }; // construct/copy/destroy flat_map() : flat_map(key_compare()) { } flat_map(key_container_type key_cont, mapped_container_type mapped_cont); template<class Allocator> flat_map(const key_container_type& key_cont, const mapped_container_type& mapped_cont, const Allocator& a); flat_map(sorted_unique_t, key_container_type key_cont, mapped_container_type mapped_cont); template<class Allocator> flat_map(sorted_unique_t, const key_container_type& key_cont, const mapped_container_type& mapped_cont, const Allocator& a); explicit flat_map(const key_compare& comp) : c(), compare(comp) { } template<class Allocator> flat_map(const key_compare& comp, const Allocator& a); template<class Allocator> explicit flat_map(const Allocator& a); template<class InputIterator> flat_map(InputIterator first, InputIterator last, const key_compare& comp = key_compare()) : c(), compare(comp) { insert(first, last); } template<class InputIterator, class Allocator> flat_map(InputIterator first, InputIterator last, const key_compare& comp, const Allocator& a); template<class InputIterator, class Allocator> flat_map(InputIterator first, InputIterator last, const Allocator& a); template</*container-compatible-range*/<value_type> R> flat_map(from_range_t fr, R&& rg) : flat_map(fr, std::forward<R>(rg), key_compare()) { } template</*container-compatible-range*/<value_type> R, class Allocator> flat_map(from_range_t, R&& rg, const Allocator& a); template</*container-compatible-range*/<value_type> R> flat_map(from_range_t, R&& rg, const key_compare& comp) : flat_map(comp) { insert_range(std::forward<R>(rg)); } template</*container-compatible-range*/<value_type> R, class Allocator> flat_map(from_range_t, R&& rg, const key_compare& comp, const Allocator& a); template<class InputIterator> flat_map(sorted_unique_t s, InputIterator first, InputIterator last, const key_compare& comp = key_compare()) : c(), compare(comp) { insert(s, first, last); } template<class InputIterator, class Allocator> flat_map(sorted_unique_t, InputIterator first, InputIterator last, const key_compare& comp, const Allocator& a); template<class InputIterator, class Allocator> flat_map(sorted_unique_t, InputIterator first, InputIterator last, const Allocator& a); flat_map(initializer_list<value_type> il, const key_compare& comp = key_compare()) : flat_map(il.begin(), il.end(), comp) { } template<class Allocator> flat_map(initializer_list<value_type> il, const key_compare& comp, const Allocator& a); template<class Allocator> flat_map(initializer_list<value_type> il, const Allocator& a); flat_map(sorted_unique_t s, initializer_list<value_type> il, const key_compare& comp = key_compare()) : flat_map(s, il.begin(), il.end(), comp) { } template<class Allocator> flat_map(sorted_unique_t, initializer_list<value_type> il, const key_compare& comp, const Allocator& a); template<class Allocator> flat_map(sorted_unique_t, initializer_list<value_type> il, const Allocator& a); flat_map& operator=(initializer_list<value_type> il); // iterators iterator begin() noexcept; const_iterator begin() const noexcept; iterator end() noexcept; const_iterator end() const noexcept; reverse_iterator rbegin() noexcept; const_reverse_iterator rbegin() const noexcept; reverse_iterator rend() noexcept; const_reverse_iterator rend() const noexcept; const_iterator cbegin() const noexcept; const_iterator cend() const noexcept; const_reverse_iterator crbegin() const noexcept; const_reverse_iterator crend() const noexcept; // capacity [[nodiscard]] bool empty() const noexcept; size_type size() const noexcept; size_type max_size() const noexcept; // element access mapped_type& operator[](const key_type& x); mapped_type& operator[](key_type&& x); template<class K> mapped_type& operator[](K&& x); mapped_type& at(const key_type& x); const mapped_type& at(const key_type& x) const; template<class K> mapped_type& at(const K& x); template<class K> const mapped_type& at(const K& x) const; // modifiers template<class... Args> pair<iterator, bool> emplace(Args&&... args); template<class... Args> iterator emplace_hint(const_iterator position, Args&&... args); pair<iterator, bool> insert(const value_type& x) { return emplace(x); } pair<iterator, bool> insert(value_type&& x) { return emplace(std::move(x)); } iterator insert(const_iterator position, const value_type& x) { return emplace_hint(position, x); } iterator insert(const_iterator position, value_type&& x) { return emplace_hint(position, std::move(x)); } template<class P> pair<iterator, bool> insert(P&& x); template<class P> iterator insert(const_iterator position, P&&); template<class InputIterator> void insert(InputIterator first, InputIterator last); template<class InputIterator> void insert(sorted_unique_t, InputIterator first, InputIterator last); template</*container-compatible-range*/<value_type> R> void insert_range(R&& rg); void insert(initializer_list<value_type> il) { insert(il.begin(), il.end()); } void insert(sorted_unique_t s, initializer_list<value_type> il) { insert(s, il.begin(), il.end()); } containers extract() &&; void replace(key_container_type&& key_cont, mapped_container_type&& mapped_cont); template<class... Args> pair<iterator, bool> try_emplace(const key_type& k, Args&&... args); template<class... Args> pair<iterator, bool> try_emplace(key_type&& k, Args&&... args); template<class K, class... Args> pair<iterator, bool> try_emplace(K&& k, Args&&... args); template<class... Args> iterator try_emplace(const_iterator hint, const key_type& k, Args&&... args); template<class... Args> iterator try_emplace(const_iterator hint, key_type&& k, Args&&... args); template<class K, class... Args> iterator try_emplace(const_iterator hint, K&& k, Args&&... args); template<class M> pair<iterator, bool> insert_or_assign(const key_type& k, M&& obj); template<class M> pair<iterator, bool> insert_or_assign(key_type&& k, M&& obj); template<class K, class M> pair<iterator, bool> insert_or_assign(K&& k, M&& obj); template<class M> iterator insert_or_assign(const_iterator hint, const key_type& k, M&& obj); template<class M> iterator insert_or_assign(const_iterator hint, key_type&& k, M&& obj); template<class K, class M> iterator insert_or_assign(const_iterator hint, K&& k, M&& obj); iterator erase(iterator position); iterator erase(const_iterator position); size_type erase(const key_type& x); template<class K> size_type erase(K&& x); iterator erase(const_iterator first, const_iterator last); void swap(flat_map& y) noexcept; void clear() noexcept; // observers key_compare key_comp() const; value_compare value_comp() const; const key_container_type& keys() const noexcept { return c.keys; } const mapped_container_type& values() const noexcept { return c.values; } // map operations iterator find(const key_type& x); const_iterator find(const key_type& x) const; template<class K> iterator find(const K& x); template<class K> const_iterator find(const K& x) const; size_type count(const key_type& x) const; template<class K> size_type count(const K& x) const; bool contains(const key_type& x) const; template<class K> bool contains(const K& x) const; iterator lower_bound(const key_type& x); const_iterator lower_bound(const key_type& x) const; template<class K> iterator lower_bound(const K& x); template<class K> const_iterator lower_bound(const K& x) const; iterator upper_bound(const key_type& x); const_iterator upper_bound(const key_type& x) const; template<class K> iterator upper_bound(const K& x); template<class K> const_iterator upper_bound(const K& x) const; pair<iterator, iterator> equal_range(const key_type& x); pair<const_iterator, const_iterator> equal_range(const key_type& x) const; template<class K> pair<iterator, iterator> equal_range(const K& x); template<class K> pair<const_iterator, const_iterator> equal_range(const K& x) const; friend bool operator==(const flat_map& x, const flat_map& y); friend /*synth-three-way-result*/<value_type> operator<=>(const flat_map& x, const flat_map& y); friend void swap(flat_map& x, flat_map& y) noexcept { x.swap(y); } private: containers c; // exposition only key_compare compare; // exposition only struct key_equiv { // exposition only key_equiv(key_compare c) : comp(c) { } bool operator()(const_reference x, const_reference y) const { return !comp(x.first, y.first) && !comp(y.first, x.first); } key_compare comp; }; }; template<class KeyContainer, class MappedContainer> flat_map(KeyContainer, MappedContainer) -> flat_map<typename KeyContainer::value_type, typename MappedContainer::value_type, less<typename KeyContainer::value_type>, KeyContainer, MappedContainer>; template<class KeyContainer, class MappedContainer, class Allocator> flat_map(KeyContainer, MappedContainer, Allocator) -> flat_map<typename KeyContainer::value_type, typename MappedContainer::value_type, less<typename KeyContainer::value_type>, KeyContainer, MappedContainer>; template<class KeyContainer, class MappedContainer> flat_map(sorted_unique_t, KeyContainer, MappedContainer) -> flat_map<typename KeyContainer::value_type, typename MappedContainer::value_type, less<typename KeyContainer::value_type>, KeyContainer, MappedContainer>; template<class KeyContainer, class MappedContainer, class Allocator> flat_map(sorted_unique_t, KeyContainer, MappedContainer, Allocator) -> flat_map<typename KeyContainer::value_type, typename MappedContainer::value_type, less<typename KeyContainer::value_type>, KeyContainer, MappedContainer>; template<class InputIterator, class Compare = less</*iter-key-type*/<InputIterator>>> flat_map(InputIterator, InputIterator, Compare = Compare()) -> flat_map</*iter-key-type*/<InputIterator>, /*iter-mapped-type*/<InputIterator>, Compare>; template<class InputIterator, class Compare = less</*iter-key-type*/<InputIterator>>> flat_map(sorted_unique_t, InputIterator, InputIterator, Compare = Compare()) -> flat_map</*iter-key-type*/<InputIterator>, /*iter-mapped-type*/<InputIterator>, Compare>; template<ranges::input_range R, class Compare = less</*range-key-type*/<R>>, class Allocator> flat_map(from_range_t, R&&, Compare = Compare(), Allocator = Allocator()) -> flat_map</*range-key-type*/<R>, /*range-mapped-type*/<R>, Compare>; template<ranges::input_range R, class Allocator> flat_map(from_range_t, R&&, Allocator) -> flat_map</*range-key-type*/<R>, /*range-mapped-type*/<R>>; template<class Key, class T, class Compare = less<Key>> flat_map(initializer_list<pair<Key, T>>, Compare = Compare()) -> flat_map<Key, T, Compare>; template<class Key, class T, class Compare = less<Key>> flat_map(sorted_unique_t, initializer_list<pair<Key, T>>, Compare = Compare()) -> flat_map<Key, T, Compare>; template<class Key, class T, class Compare, class KeyContainer, class MappedContainer, class Allocator> struct uses_allocator<flat_map<Key, T, Compare, KeyContainer, MappedContainer>, Allocator> : bool_constant<uses_allocator_v<KeyContainer, Allocator> && uses_allocator_v<MappedContainer, Allocator>> { }; } ``` #### Class template `std::flat_multimap` ``` namespace std { template<class Key, class T, class Compare = less<Key>, class KeyContainer = vector<Key>, class MappedContainer = vector<T>> class flat_multimap { public: // types using key_type = Key; using mapped_type = T; using value_type = pair<key_type, mapped_type>; using key_compare = Compare; using reference = pair<const key_type&, mapped_type&>; using const_reference = pair<const key_type&, const mapped_type&>; using size_type = size_t; using difference_type = ptrdiff_t; using iterator = /* implementation-defined */; using const_iterator = /* implementation-defined */; using reverse_iterator = std::reverse_iterator<iterator>; using const_reverse_iterator = std::reverse_iterator<const_iterator>; using key_container_type = KeyContainer; using mapped_container_type = MappedContainer; class value_compare { private: key_compare comp; // exposition only value_compare(key_compare c) : comp(c) { } // exposition only public: bool operator()(const_reference x, const_reference y) const { return comp(x.first, y.first); } }; struct containers { key_container_type keys; mapped_container_type values; }; // construct/copy/destroy flat_multimap() : flat_multimap(key_compare()) { } flat_multimap(key_container_type key_cont, mapped_container_type mapped_cont); template<class Allocator> flat_multimap(const key_container_type& key_cont, const mapped_container_type& mapped_cont, const Allocator& a); flat_multimap(sorted_equivalent_t, key_container_type key_cont, mapped_container_type mapped_cont); template<class Allocator> flat_multimap(sorted_equivalent_t, const key_container_type& key_cont, const mapped_container_type& mapped_cont, const Allocator& a); explicit flat_multimap(const key_compare& comp) : c(), compare(comp) { } template<class Allocator> flat_multimap(const key_compare& comp, const Allocator& a); template<class Allocator> explicit flat_multimap(const Allocator& a); template<class InputIterator> flat_multimap(InputIterator first, InputIterator last, const key_compare& comp = key_compare()) : c(), compare(comp) { insert(first, last); } template<class InputIterator, class Allocator> flat_multimap(InputIterator first, InputIterator last, const key_compare& comp, const Allocator& a); template<class InputIterator, class Allocator> flat_multimap(InputIterator first, InputIterator last, const Allocator& a); template</*container-compatible-range*/<value_type> R> flat_mutlimap(from_range_t fr, R&& rg) : flat_multimap(fr, std::forward<R>(rg), key_compare()) { } template</*container-compatible-range*/<value_type> R, class Allocator> flat_mutlimap(from_range_t, R&& rg, const Allocator& a); template</*container-compatible-range*/<value_type> R> flat_multimap(from_range_t, R&& rg, const key_compare& comp) : flat_multimap(comp) { insert_range(std::forward<R>(rg)); } template</*container-compatible-range*/<value_type> R, class Allocator> flat_multimap(from_range_t, R&& rg, const key_compare& comp, const Allocator& a); template<class InputIterator> flat_multimap(sorted_equivalent_t s, InputIterator first, InputIterator last, const key_compare& comp = key_compare()) : c(), compare(comp) { insert(s, first, last); } template<class InputIterator, class Allocator> flat_multimap(sorted_equivalent_t, InputIterator first, InputIterator last, const key_compare& comp, const Allocator& a); template<class InputIterator, class Allocator> flat_multimap(sorted_equivalent_t, InputIterator first, InputIterator last, const Allocator& a); flat_multimap(initializer_list<value_type> il, const key_compare& comp = key_compare()) : flat_multimap(il.begin(), il.end(), comp) { } template<class Allocator> flat_multimap(initializer_list<value_type> il, const key_compare& comp, const Allocator& a); template<class Allocator> flat_multimap(initializer_list<value_type> il, const Allocator& a); flat_multimap(sorted_equivalent_t s, initializer_list<value_type> il, const key_compare& comp = key_compare()) : flat_multimap(s, il.begin(), il.end(), comp) { } template<class Allocator> flat_multimap(sorted_equivalent_t, initializer_list<value_type> il, const key_compare& comp, const Allocator& a); template<class Allocator> flat_multimap(sorted_equivalent_t, initializer_list<value_type> il, const Allocator& a); flat_multimap& operator=(initializer_list<value_type> il); // iterators iterator begin() noexcept; const_iterator begin() const noexcept; iterator end() noexcept; const_iterator end() const noexcept; reverse_iterator rbegin() noexcept; const_reverse_iterator rbegin() const noexcept; reverse_iterator rend() noexcept; const_reverse_iterator rend() const noexcept; const_iterator cbegin() const noexcept; const_iterator cend() const noexcept; const_reverse_iterator crbegin() const noexcept; const_reverse_iterator crend() const noexcept; // capacity [[nodiscard]] bool empty() const noexcept; size_type size() const noexcept; size_type max_size() const noexcept; // modifiers template<class... Args> iterator emplace(Args&&... args); template<class... Args> iterator emplace_hint(const_iterator position, Args&&... args); iterator insert(const value_type& x) { return emplace(x); } iterator insert(value_type&& x) { return emplace(std::move(x)); } iterator insert(const_iterator position, const value_type& x) { return emplace_hint(position, x); } iterator insert(const_iterator position, value_type&& x) { return emplace_hint(position, std::move(x)); } template<class P> iterator insert(P&& x); template<class P> iterator insert(const_iterator position, P&&); template<class InputIterator> void insert(InputIterator first, InputIterator last); template<class InputIterator> void insert(sorted_equivalent_t, InputIterator first, InputIterator last); template</*container-compatible-range*/<value_type> R> void insert_range(R&& rg); void insert(initializer_list<value_type> il) { insert(il.begin(), il.end()); } void insert(sorted_equivalent_t s, initializer_list<value_type> il) { insert(s, il.begin(), il.end()); } containers extract() &&; void replace(key_container_type&& key_cont, mapped_container_type&& mapped_cont); iterator erase(iterator position); iterator erase(const_iterator position); size_type erase(const key_type& x); template<class K> size_type erase(K&& x); iterator erase(const_iterator first, const_iterator last); void swap(flat_multimap&) noexcept; void clear() noexcept; // observers key_compare key_comp() const; value_compare value_comp() const; const key_container_type& keys() const noexcept { return c.keys; } const mapped_container_type& values() const noexcept { return c.values; } // map operations iterator find(const key_type& x); const_iterator find(const key_type& x) const; template<class K> iterator find(const K& x); template<class K> const_iterator find(const K& x) const; size_type count(const key_type& x) const; template<class K> size_type count(const K& x) const; bool contains(const key_type& x) const; template<class K> bool contains(const K& x) const; iterator lower_bound(const key_type& x); const_iterator lower_bound(const key_type& x) const; template<class K> iterator lower_bound(const K& x); template<class K> const_iterator lower_bound(const K& x) const; iterator upper_bound(const key_type& x); const_iterator upper_bound(const key_type& x) const; template<class K> iterator upper_bound(const K& x); template<class K> const_iterator upper_bound(const K& x) const; pair<iterator, iterator> equal_range(const key_type& x); pair<const_iterator, const_iterator> equal_range(const key_type& x) const; template<class K> pair<iterator, iterator> equal_range(const K& x); template<class K> pair<const_iterator, const_iterator> equal_range(const K& x) const; friend bool operator==(const flat_multimap& x, const flat_multimap& y); friend /*synth-three-way-result*/<value_type> operator<=>(const flat_multimap& x, const flat_multimap& y); friend void swap(flat_multimap& x, flat_multimap& y) noexcept { x.swap(y); } private: containers c; // exposition only key_compare compare; // exposition only }; template<class KeyContainer, class MappedContainer> flat_multimap(KeyContainer, MappedContainer) -> flat_multimap<typename KeyContainer::value_type, typename MappedContainer::value_type, less<typename KeyContainer::value_type>, KeyContainer, MappedContainer>; template<class KeyContainer, class MappedContainer, class Allocator> flat_multimap(KeyContainer, MappedContainer, Allocator) -> flat_multimap<typename KeyContainer::value_type, typename MappedContainer::value_type, less<typename KeyContainer::value_type>, KeyContainer, MappedContainer>; template<class KeyContainer, class MappedContainer> flat_multimap(sorted_equivalent_t, KeyContainer, MappedContainer) -> flat_multimap<typename KeyContainer::value_type, typename MappedContainer::value_type, less<typename KeyContainer::value_type>, KeyContainer, MappedContainer>; template<class KeyContainer, class MappedContainer, class Allocator> flat_multimap(sorted_equivalent_t, KeyContainer, MappedContainer, Allocator) -> flat_multimap<typename KeyContainer::value_type, typename MappedContainer::value_type, less<typename KeyContainer::value_type>, KeyContainer, MappedContainer>; template<class InputIterator, class Compare = less</*iter-key-type*/<InputIterator>>> flat_multimap(InputIterator, InputIterator, Compare = Compare()) -> flat_multimap</*iter-key-type*/<InputIterator>, /*iter-mapped-type*/<InputIterator>, Compare>; template<class InputIterator, class Compare = less</*iter-key-type*/<InputIterator>>> flat_multimap(sorted_equivalent_t, InputIterator, InputIterator, Compare = Compare()) -> flat_multimap</*iter-key-type*/<InputIterator>, /*iter-mapped-type*/<InputIterator>, Compare>; template<ranges::input_range R, class Compare = less</*range-key-type*/<R>>, class Allocator> flat_multimap(from_range_t, R&&, Compare = Compare(), Allocator = Allocator()) -> flat_multimap</*range-key-type*/<R>, /*range-mapped-type*/<R>, Compare>; template<ranges::input_range R, class Allocator> flat_multimap(from_range_t, R&&, Allocator) -> flat_multimap</*range-key-type*/<R>, /*range-mapped-type*/<R>>; template<class Key, class T, class Compare = less<Key>> flat_multimap(initializer_list<pair<Key, T>>, Compare = Compare()) -> flat_multimap<Key, T, Compare>; template<class Key, class T, class Compare = less<Key>> flat_multimap(sorted_equivalent_t, initializer_list<pair<Key, T>>, Compare = Compare()) -> flat_multimap<Key, T, Compare>; template<class Key, class T, class Compare, class KeyContainer, class MappedContainer, class Allocator> struct uses_allocator<flat_multimap<Key, T, Compare, KeyContainer, MappedContainer>, Allocator> : bool_constant<uses_allocator_v<KeyContainer, Allocator> && uses_allocator_v<MappedContainer, Allocator>> { }; } ``` ### References * C++23 standard (ISO/IEC 14882:2023): + 24.6.4 Header `<flat_map>` synopsis [flat.map.syn] + 24.6.9.2 Definition [flat.map.defn] + 24.6.10.2 Definition [flat.multimap.defn]
programming_docs
cpp Standard library header <iostream> Standard library header <iostream> ================================== This header is part of the [Input/output](../io "cpp/io") library. Including `<iostream>` behaves as if it defines a static storage duration object of type `[std::ios\_base::Init](../io/ios_base/init "cpp/io/ios base/Init")`, whose constructor initializes the standard stream objects if it is the first `std::ios_base::Init` object to be constructed, and whose destructor flushes those objects (except for `cin` and `wcin`) if it is the last `std::ios_base::Init` object to be destroyed. | | | --- | | Includes | | [<ios>](ios "cpp/header/ios") (C++11) | `[std::ios\_base](../io/ios_base "cpp/io/ios base")` class, `[std::basic\_ios](../io/basic_ios "cpp/io/basic ios")` class template and several typedefs | | [<streambuf>](streambuf "cpp/header/streambuf") (C++11) | `[std::basic\_streambuf](../io/basic_streambuf "cpp/io/basic streambuf")` class template | | [<istream>](istream "cpp/header/istream") (C++11) | `[std::basic\_istream](../io/basic_istream "cpp/io/basic istream")` class template and several typedefs | | [<ostream>](ostream "cpp/header/ostream") (C++11) | `[std::basic\_ostream](../io/basic_ostream "cpp/io/basic ostream")`, `[std::basic\_iostream](../io/basic_iostream "cpp/io/basic iostream")` class templates and several typedefs | | Objects | | [cinwcin](../io/cin "cpp/io/cin") | reads from the standard C input stream `[stdin](../io/c/std_streams "cpp/io/c/std streams")` (global object) | | [coutwcout](../io/cout "cpp/io/cout") | writes to the standard C output stream `[stdout](../io/c/std_streams "cpp/io/c/std streams")`(global object) | | [cerrwcerr](../io/cerr "cpp/io/cerr") | writes to the standard C error stream `[stderr](../io/c/std_streams "cpp/io/c/std streams")`, unbuffered(global object) | | [clogwclog](../io/clog "cpp/io/clog") | writes to the standard C error stream `[stderr](../io/c/std_streams "cpp/io/c/std streams")`(global object) | ### Synopsis ``` #include <ios> #include <streambuf> #include <istream> #include <ostream> namespace std { extern istream cin; extern ostream cout; extern ostream cerr; extern ostream clog; extern wistream wcin; extern wostream wcout; extern wostream wcerr; extern wostream wclog; } ``` cpp Standard library header <memory_resource> (C++17) Standard library header <memory\_resource> (C++17) ================================================== | | | --- | | Classes | | Defined in namespace `std::pmr` | | [polymorphic\_allocator](../memory/polymorphic_allocator "cpp/memory/polymorphic allocator") (C++17) | an allocator that supports run-time polymorphism based on the `[std::pmr::memory\_resource](../memory/memory_resource "cpp/memory/memory resource")` it is constructed with (class template) | | [memory\_resource](../memory/memory_resource "cpp/memory/memory resource") (C++17) | an abstract interface for classes that encapsulate memory resources (class) | | [pool\_options](../memory/pool_options "cpp/memory/pool options") (C++17) | a set of constructor options for pool resources (class) | | [synchronized\_pool\_resource](../memory/synchronized_pool_resource "cpp/memory/synchronized pool resource") (C++17) | a thread-safe `[std::pmr::memory\_resource](../memory/memory_resource "cpp/memory/memory resource")` for managing allocations in pools of different block sizes (class) | | [unsynchronized\_pool\_resource](../memory/unsynchronized_pool_resource "cpp/memory/unsynchronized pool resource") (C++17) | a thread-unsafe `[std::pmr::memory\_resource](../memory/memory_resource "cpp/memory/memory resource")` for managing allocations in pools of different block sizes (class) | | [monotonic\_buffer\_resource](../memory/monotonic_buffer_resource "cpp/memory/monotonic buffer resource") (C++17) | a special-purpose `[std::pmr::memory\_resource](../memory/memory_resource "cpp/memory/memory resource")` that releases the allocated memory only when the resource is destroyed (class) | | Functions | | Defined in namespace `std::pmr` | | [new\_delete\_resource](../memory/new_delete_resource "cpp/memory/new delete resource") (C++17) | returns a static program-wide `[std::pmr::memory\_resource](../memory/memory_resource "cpp/memory/memory resource")` that uses the global `[operator new](../memory/new/operator_new "cpp/memory/new/operator new")` and `[operator delete](../memory/new/operator_delete "cpp/memory/new/operator delete")` to allocate and deallocate memory (function) | | [null\_memory\_resource](../memory/null_memory_resource "cpp/memory/null memory resource") (C++17) | returns a static `[std::pmr::memory\_resource](../memory/memory_resource "cpp/memory/memory resource")` that performs no allocation (function) | | [get\_default\_resource](../memory/get_default_resource "cpp/memory/get default resource") (C++17) | gets the default `[std::pmr::memory\_resource](../memory/memory_resource "cpp/memory/memory resource")` (function) | | [set\_default\_resource](../memory/set_default_resource "cpp/memory/set default resource") (C++17) | sets the default `[std::pmr::memory\_resource](../memory/memory_resource "cpp/memory/memory resource")` (function) | ### Synopsis ``` namespace std::pmr { // class memory_resource class memory_resource; bool operator==(const memory_resource& a, const memory_resource& b) noexcept; // class template polymorphic_allocator template<class Tp> class polymorphic_allocator; template<class T1, class T2> bool operator==(const polymorphic_allocator<T1>& a, const polymorphic_allocator<T2>& b) noexcept; // global memory resources memory_resource* new_delete_resource() noexcept; memory_resource* null_memory_resource() noexcept; memory_resource* set_default_resource(memory_resource* r) noexcept; memory_resource* get_default_resource() noexcept; // pool resource classes struct pool_options; class synchronized_pool_resource; class unsynchronized_pool_resource; class monotonic_buffer_resource; } ``` #### Class `[std::pmr::memory\_resource](../memory/memory_resource "cpp/memory/memory resource")` ``` namespace std::pmr { class memory_resource { static constexpr size_t max_align = alignof(max_align_t); // exposition only public: memory_resource() = default; memory_resource(const memory_resource&) = default; virtual ~memory_resource(); memory_resource& operator=(const memory_resource&) = default; [[nodiscard]] void* allocate(size_t bytes, size_t alignment = max_align); void deallocate(void* p, size_t bytes, size_t alignment = max_align); bool is_equal(const memory_resource& other) const noexcept; private: virtual void* do_allocate(size_t bytes, size_t alignment) = 0; virtual void do_deallocate(void* p, size_t bytes, size_t alignment) = 0; virtual bool do_is_equal(const memory_resource& other) const noexcept = 0; }; } ``` #### Class template `[std::pmr::polymorphic\_allocator](../memory/polymorphic_allocator "cpp/memory/polymorphic allocator")` ``` namespace std::pmr { template<class Tp = byte> class polymorphic_allocator { memory_resource* memory_rsrc; // exposition only public: using value_type = Tp; // constructors polymorphic_allocator() noexcept; polymorphic_allocator(memory_resource* r); polymorphic_allocator(const polymorphic_allocator& other) = default; template<class U> polymorphic_allocator(const polymorphic_allocator<U>& other) noexcept; polymorphic_allocator& operator=(const polymorphic_allocator&) = delete; // member functions [[nodiscard]] Tp* allocate(size_t n); void deallocate(Tp* p, size_t n); [[nodiscard]] void* allocate_bytes(size_t nbytes, size_t alignment = alignof(max_align_t)); void deallocate_bytes(void* p, size_t nbytes, size_t alignment = alignof(max_align_t)); template<class T> [[nodiscard]] T* allocate_object(size_t n = 1); template<class T> void deallocate_object(T* p, size_t n = 1); template<class T, class... CtorArgs> [[nodiscard]] T* new_object(CtorArgs&&... ctor_args); template<class T> void delete_object(T* p); template<class T, class... Args> void construct(T* p, Args&&... args); template<class T> void destroy(T* p); // deprecated polymorphic_allocator select_on_container_copy_construction() const; memory_resource* resource() const; }; } ``` #### Class `[std::pmr::pool\_options](../memory/pool_options "cpp/memory/pool options")` ``` namespace std::pmr { struct pool_options { size_t max_blocks_per_chunk = 0; size_t largest_required_pool_block = 0; }; } ``` #### Class `[std::pmr::synchronized\_pool\_resource](../memory/synchronized_pool_resource "cpp/memory/synchronized pool resource")` ``` namespace std::pmr { class synchronized_pool_resource : public memory_resource { public: synchronized_pool_resource(const pool_options& opts, memory_resource* upstream); synchronized_pool_resource() : synchronized_pool_resource(pool_options(), get_default_resource()) {} explicit synchronized_pool_resource(memory_resource* upstream) : synchronized_pool_resource(pool_options(), upstream) {} explicit synchronized_pool_resource(const pool_options& opts) : synchronized_pool_resource(opts, get_default_resource()) {} synchronized_pool_resource(const synchronized_pool_resource&) = delete; virtual ~synchronized_pool_resource(); synchronized_pool_resource& operator=(const synchronized_pool_resource&) = delete; void release(); memory_resource* upstream_resource() const; pool_options options() const; protected: void* do_allocate(size_t bytes, size_t alignment) override; void do_deallocate(void* p, size_t bytes, size_t alignment) override; bool do_is_equal(const memory_resource& other) const noexcept override; }; } ``` #### Class `[std::pmr::unsynchronized\_pool\_resource](../memory/unsynchronized_pool_resource "cpp/memory/unsynchronized pool resource")` ``` namespace std::pmr { class unsynchronized_pool_resource : public memory_resource { public: unsynchronized_pool_resource(const pool_options& opts, memory_resource* upstream); unsynchronized_pool_resource() : unsynchronized_pool_resource(pool_options(), get_default_resource()) {} explicit unsynchronized_pool_resource(memory_resource* upstream) : unsynchronized_pool_resource(pool_options(), upstream) {} explicit unsynchronized_pool_resource(const pool_options& opts) : unsynchronized_pool_resource(opts, get_default_resource()) {} unsynchronized_pool_resource(const unsynchronized_pool_resource&) = delete; virtual ~unsynchronized_pool_resource(); unsynchronized_pool_resource& operator=(const unsynchronized_pool_resource&) = delete; void release(); memory_resource* upstream_resource() const; pool_options options() const; protected: void* do_allocate(size_t bytes, size_t alignment) override; void do_deallocate(void* p, size_t bytes, size_t alignment) override; bool do_is_equal(const memory_resource& other) const noexcept override; }; } ``` #### Class `[std::pmr::monotonic\_buffer\_resource](../memory/monotonic_buffer_resource "cpp/memory/monotonic buffer resource")` ``` namespace std::pmr { class monotonic_buffer_resource : public memory_resource { memory_resource* upstream_rsrc; // exposition only void* current_buffer; // exposition only size_t next_buffer_size; // exposition only public: explicit monotonic_buffer_resource(memory_resource* upstream); monotonic_buffer_resource(size_t initial_size, memory_resource* upstream); monotonic_buffer_resource(void* buffer, size_t buffer_size, memory_resource* upstream); monotonic_buffer_resource() : monotonic_buffer_resource(get_default_resource()) {} explicit monotonic_buffer_resource(size_t initial_size) : monotonic_buffer_resource(initial_size, get_default_resource()) {} monotonic_buffer_resource(void* buffer, size_t buffer_size) : monotonic_buffer_resource(buffer, buffer_size, get_default_resource()) {} monotonic_buffer_resource(const monotonic_buffer_resource&) = delete; virtual ~monotonic_buffer_resource(); monotonic_buffer_resource& operator=(const monotonic_buffer_resource&) = delete; void release(); memory_resource* upstream_resource() const; protected: void* do_allocate(size_t bytes, size_t alignment) override; void do_deallocate(void* p, size_t bytes, size_t alignment) override; bool do_is_equal(const memory_resource& other) const noexcept override; }; } ``` cpp Standard library header <generator> (C++23) Standard library header <generator> (C++23) =========================================== This header is part of the [ranges](../ranges "cpp/ranges") library. | | | --- | | Classes | [Template:cpp/ranges/dsc generator](https://en.cppreference.com/mwiki/index.php?title=Template:cpp/ranges/dsc_generator&action=edit&redlink=1 "Template:cpp/ranges/dsc generator (page does not exist)") ### Synopsis ``` namespace std { // class template generator template<class Ref, class V = void, class Allocator = void> class generator; } ``` #### Class template `std::generator` ``` namespace std { template<class Ref, class V = void, class Allocator = void> class generator : public ranges::view_interface<generator<Ref, V, Allocator>> { private: using value = conditional_t<is_void_v<V>, remove_cvref_t< Ref >, V>; // exposition only using reference = conditional_t<is_void_v<V>, Ref&&, Ref>; // exposition only // class generator::iterator class iterator; // exposition only public: using yielded = conditional_t<is_reference_v<reference>, reference, const reference&>; // class generator::promise_type class promise_type; generator(const generator&) = delete; generator(generator&& other) noexcept; ~generator(); generator& operator=(generator other) noexcept; iterator begin(); default_sentinel_t end() const noexcept; private: coroutine_handle<promise_type> coroutine_ = nullptr; // exposition only unique_ptr<stack<coroutine_handle<>>> active_; // exposition only }; } ``` #### Class `std::generator::promise_type` ``` namespace std { template<class Ref, class V, class Allocator> class generator<Ref, V, Allocator>::promise_type { public: generator get_return_object() noexcept; suspend_always initial_suspend() const noexcept { return {}; } auto final_suspend() noexcept; suspend_always yield_value(yielded val) noexcept; auto yield_value(const remove_reference_t<yielded>& lval) requires is_rvalue_reference_v<yielded> && constructible_from<remove_cvref_t<yielded>, const remove_reference_t<yielded>&>; template<class R2, class V2, class Alloc2, class Unused> requires same_as<typename generator<T2, V2, Alloc2>::yielded, yielded> auto yield_value(ranges::elements_of<generator<T2, V2, Alloc2>&&, Unused> g) noexcept; template<ranges::input_range R, class Alloc> requires convertible_to<ranges::range_reference_t<R>, yielded> auto yield_value(ranges::elements_of<R, Alloc> r) noexcept; void await_transform() = delete; void return_void() const noexcept {} void unhandled_exception(); void* operator new(size_t size) requires same_as<Allocator, void> || default_initializable<Allocator>; template<class Alloc, class... Args> requires same_as<Allocator, void> || convertible_to<const Alloc&, Allocator> void* operator new(size_t size, allocator_arg_t, const Alloc& alloc, const Args&...); template<class This, class Alloc, class... Args> requires same_as<Allocator, void> || convertible_to<const Alloc&, Allocator> void* operator new(size_t size, const This&, allocator_arg_t, const Alloc& alloc, const Args&...); void operator delete(void* pointer, size_t size) noexcept; private: add_pointer_t<yielded> value_ = nullptr; // exposition only exception_ptr except_; // exposition only }; } ``` #### Class `std::generator::iterator` ``` namespace std { template<class Ref, class V, class Allocator> class generator<Ref, V, Allocator>::iterator { public: using value_type = value; using difference_type = ptrdiff_t; iterator(iterator&& other) noexcept; iterator& operator=(iterator&& other) noexcept; reference operator*() const noexcept(is_nothrow_copy_constructible_v<reference>); iterator& operator++(); void operator++(int); friend bool operator==(iterator i, default_sentinel_t); private: coroutine_handle<promise_type> coroutine_; // exposition only }; } ``` ### References * C++23 standard (ISO/IEC 14882:2023): + 26.8.2 Header `<generator>` synopsis [generator.syn] + 26.8.3 Class template generator [coro.generator.class] + 26.8.5 Class generator::promise\_type [coro.generator.promise] + 26.8.6 Class generator::iterator [coro.generator.iterator] cpp Standard library header <stack> Standard library header <stack> =============================== This header is part of the [containers](../container "cpp/container") library. | | | --- | | Includes | | [<compare>](compare "cpp/header/compare") (C++20) | [Three-way comparison operator](../language/operator_comparison#Three-way_comparison "cpp/language/operator comparison") support | | [<initializer\_list>](initializer_list "cpp/header/initializer list") (C++11) | `[std::initializer\_list](../utility/initializer_list "cpp/utility/initializer list")` class template | | Classes | | [stack](../container/stack "cpp/container/stack") | adapts a container to provide stack (LIFO data structure) (class template) | | [std::uses\_allocator<std::stack>](../container/stack/uses_allocator "cpp/container/stack/uses allocator") (C++11) | specializes the `[std::uses\_allocator](../memory/uses_allocator "cpp/memory/uses allocator")` type trait (class template specialization) | | Functions | | [operator==operator!=operator<operator<=operator>operator>=operator<=>](../container/stack/operator_cmp "cpp/container/stack/operator cmp") (C++20) | lexicographically compares the values in the stack (function template) | | [std::swap(std::stack)](../container/stack/swap2 "cpp/container/stack/swap2") (C++11) | specializes the `[std::swap](../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | ### Synopsis ``` #include <compare> #include <initializer_list> namespace std { template<class T, class Container = deque<T>> class stack; template<class T, class Container> bool operator==(const stack<T, Container>& x, const stack<T, Container>& y); template<class T, class Container> bool operator!=(const stack<T, Container>& x, const stack<T, Container>& y); template<class T, class Container> bool operator< (const stack<T, Container>& x, const stack<T, Container>& y); template<class T, class Container> bool operator> (const stack<T, Container>& x, const stack<T, Container>& y); template<class T, class Container> bool operator<=(const stack<T, Container>& x, const stack<T, Container>& y); template<class T, class Container> bool operator>=(const stack<T, Container>& x, const stack<T, Container>& y); template<class T, three_way_comparable Container> compare_three_way_result_t<Container> operator<=>(const stack<T, Container>& x, const stack<T, Container>& y); template<class T, class Container> void swap(stack<T, Container>& x, stack<T, Container>& y) noexcept(noexcept(x.swap(y))); template<class T, class Container, class Alloc> struct uses_allocator<stack<T, Container>, Alloc>; } ``` #### Class template `[std::stack](../container/stack "cpp/container/stack")` ``` namespace std { template<class T, class Container = deque<T>> class stack { public: using value_type = typename Container::value_type; using reference = typename Container::reference; using const_reference = typename Container::const_reference; using size_type = typename Container::size_type; using container_type = Container; protected: Container c; public: stack() : stack(Container()) {} explicit stack(const Container&); explicit stack(Container&&); template<class InputIt> stack(InputIt first, InputIt last); template<class Alloc> explicit stack(const Alloc&); template<class Alloc> stack(const Container&, const Alloc&); template<class Alloc> stack(Container&&, const Alloc&); template<class Alloc> stack(const stack&, const Alloc&); template<class Alloc> stack(stack&&, const Alloc&); template<class InputIt, class Alloc> stack(InputIt first, InputIt last, const Alloc&); [[nodiscard]] bool empty() const { return c.empty(); } size_type size() const { return c.size(); } reference top() { return c.back(); } const_reference top() const { return c.back(); } void push(const value_type& x) { c.push_back(x); } void push(value_type&& x) { c.push_back(std::move(x)); } template<class... Args> decltype(auto) emplace(Args&&... args) { return c.emplace_back(std::forward<Args>(args)...); } void pop() { c.pop_back(); } void swap(stack& s) noexcept(is_nothrow_swappable_v<Container>) { using std::swap; swap(c, s.c); } }; template<class Container> stack(Container) -> stack<typename Container::value_type, Container>; template<class InputIt> stack(InputIt, InputIt) -> stack</*iter-value-type*/<InputIt>>; template<class Container, class Allocator> stack(Container, Allocator) -> stack<typename Container::value_type, Container>; template<class InputIt, class Allocator> stack(InputIt, InputIt, Allocator) -> stack</*iter-value-type*/<InputIt>, deque</*iter-value-type*/<InputIt>, Allocator>>; template<class T, class Container, class Alloc> struct uses_allocator<stack<T, Container>, Alloc> : uses_allocator<Container, Alloc>::type { }; } ```
programming_docs
cpp std::stacktrace_entry std::stacktrace\_entry ====================== | Defined in header `[<stacktrace>](../header/stacktrace "cpp/header/stacktrace")` | | | | --- | --- | --- | | ``` class stacktrace_entry; ``` | | (since C++23) | The `stacktrace_entry` class provides operations for querying information about an evaluation in a stacktrace. Each `stacktrace_entry` object is either empty, or represents an evaluation in a stacktrace. `stacktrace_entry` models `[std::regular](http://en.cppreference.com/w/cpp/concepts/regular)` and `[std::three\_way\_comparable](http://en.cppreference.com/w/cpp/utility/compare/three_way_comparable)<[std::strong\_ordering](http://en.cppreference.com/w/cpp/utility/compare/strong_ordering)>`. ### Member types | | | | --- | --- | | `native_handle_type`(C++23) | implementation-defined native handle type | ### Member functions | | | | --- | --- | | [(constructor)](stacktrace_entry/stacktrace_entry "cpp/utility/stacktrace entry/stacktrace entry") (C++23) | constructs a new `stacktrace_entry` (public member function) | | (destructor) (C++23) | destroys the `stacktrace_entry` (public member function) | | [operator=](stacktrace_entry/operator= "cpp/utility/stacktrace entry/operator=") (C++23) | assigns the contents of one `stacktrace_entry` to another (public member function) | | Observers | | [native\_handle](stacktrace_entry/native_handle "cpp/utility/stacktrace entry/native handle") (C++23) | gets the implementation-defined native handle of the `stacktrace_entry` (public member function) | | [operator bool](stacktrace_entry/operator_bool "cpp/utility/stacktrace entry/operator bool") (C++23) | checks whether the `stacktrace_entry` is empty (public member function) | | Query | | [description](stacktrace_entry/description "cpp/utility/stacktrace entry/description") (C++23) | gets the description of the evaluation represented by the `stacktrace_entry` (public member function) | | [source\_file](stacktrace_entry/source_file "cpp/utility/stacktrace entry/source file") (C++23) | gets the name of the source file that lexically contains the expression or statement whose evaluation is represented by the `stacktrace_entry` (public member function) | | [source\_line](stacktrace_entry/source_line "cpp/utility/stacktrace entry/source line") (C++23) | gets the line number that lexically relates the evaluation represented by the `stacktrace_entry` (public member function) | ### Non-member functions | | | | --- | --- | | [operator==operator<=>](stacktrace_entry/operator_cmp "cpp/utility/stacktrace entry/operator cmp") (C++23) | compares two `stacktrace_entry` values (function) | | [to\_string](stacktrace_entry/to_string "cpp/utility/stacktrace entry/to string") (C++23) | returns a string with a description of the `stacktrace_entry` (function) | | [operator<<](stacktrace_entry/operator_ltlt "cpp/utility/stacktrace entry/operator ltlt") (C++23) | performs stream output of `stacktrace_entry` (function template) | ### Helper classes | | | | --- | --- | | [std::hash<std::stacktrace\_entry>](stacktrace_entry/hash "cpp/utility/stacktrace entry/hash") (C++23) | hash support for `std::stacktrace_entry` (class template specialization) | ### Notes `boost::stacktrace::frame` (available in [Boost.Stacktrace](https://www.boost.org/doc/libs/release/doc/html/stacktrace.html)) can be used instead when `std::stacktrace_entry` is not available. | [Feature-test](feature_test "cpp/utility/feature test") macro | Value | Std | | --- | --- | --- | | [`__cpp_lib_stacktrace`](../feature_test#Library_features "cpp/feature test") | `202011L` | (C++23) | ### Example ### See also | | | | --- | --- | | [basic\_stacktrace](basic_stacktrace "cpp/utility/basic stacktrace") (C++23) | approximate representation of an invocation sequence consists of stacktrace entries (class template) | | [source\_location](source_location "cpp/utility/source location") (C++20) | A class representing information about the source code, such as file names, line numbers, and function names (class) | cpp std::make_from_tuple std::make\_from\_tuple ====================== | Defined in header `[<tuple>](../header/tuple "cpp/header/tuple")` | | | | --- | --- | --- | | ``` template< class T, class Tuple > constexpr T make_from_tuple( Tuple&& t ); ``` | | (since C++17) | Construct an object of type `T`, using the elements of the tuple `t` as the arguments to the constructor. The program is ill-formed if the hypothetical variable definition `T var([std::get](http://en.cppreference.com/w/cpp/utility/variant/get)<Is>([std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Tuple>(t))...);` is ill-formed, or `T` is a reference type and `var` is [bound to a temporary object](../language/reference_initialization#Lifetime_of_a_temporary "cpp/language/reference initialization") (since C++23), where `Is...` denotes the parameter pack `0, 1, ..., [std::tuple\_size\_v](http://en.cppreference.com/w/cpp/utility/tuple/tuple_size)<[std::remove\_reference\_t](http://en.cppreference.com/w/cpp/types/remove_reference)<Tuple>> - 1`. ### Parameters | | | | | --- | --- | --- | | t | - | tuple whose elements to be used as arguments to the constructor of `T` | ### Return value The constructed `T` object or reference. ### Notes The tuple need not be `[std::tuple](tuple "cpp/utility/tuple")`, and instead may be anything that supports `[std::get](variant/get "cpp/utility/variant/get")` and `std::tuple_size`; in particular, `[std::array](../container/array "cpp/container/array")` and `[std::pair](pair "cpp/utility/pair")` may be used. Due to [guaranteed copy elision](../language/copy_elision "cpp/language/copy elision"), `T` need not be movable. | [Feature-test](feature_test "cpp/utility/feature test") macro | | --- | | [`__cpp_lib_make_from_tuple`](../feature_test#Library_features "cpp/feature test") | ### Possible implementation | | | --- | | ``` namespace detail { template<class T, class Tuple, std::size_t... I> constexpr T make_from_tuple_impl(Tuple&& t, std::index_sequence<I...>) { static_assert(std::is_constructible_v<T, decltype(std::get<I>(std::declval<Tuple>()))...>); #if __cpp_lib_reference_from_temporary >= 202202L if constexpr (std::tuple_size_v<std::remove_reference_t<Tuple>> == 1) { using tuple_first_t = decltype(std::get<0>(std::declval<Tuple>())); static_assert(!std::reference_constructs_from_temporary_v<T, tuple_first_t>); } #endif return T(std::get<I>(std::forward<Tuple>(t))...); } } // namespace detail template<class T, class Tuple> constexpr T make_from_tuple(Tuple&& t) { return detail::make_from_tuple_impl<T>(std::forward<Tuple>(t), std::make_index_sequence<std::tuple_size_v<std::remove_reference_t<Tuple>>>{}); } ``` | ### Example ``` #include <iostream> #include <tuple> struct Foo { Foo(int first, float second, int third) { std::cout << first << ", " << second << ", " << third << "\n"; } }; int main() { auto tuple = std::make_tuple(42, 3.14f, 0); std::make_from_tuple<Foo>(std::move(tuple)); } ``` Output: ``` 42, 3.14, 0 ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 3528](https://cplusplus.github.io/LWG/issue3528) | C++17 | cast containing `reinterpret_cast` etc. was allowed in the case of 1-tuple | disallowed | ### See also | | | | --- | --- | | [make\_tuple](tuple/make_tuple "cpp/utility/tuple/make tuple") (C++11) | creates a `tuple` object of the type defined by the argument types (function template) | | [forward\_as\_tuple](tuple/forward_as_tuple "cpp/utility/tuple/forward as tuple") (C++11) | creates a `tuple` of [forwarding references](../language/reference#Forwarding_references "cpp/language/reference") (function template) | | [apply](apply "cpp/utility/apply") (C++17) | calls a function with a tuple of arguments (function template) | cpp std::declval std::declval ============ | Defined in header `[<utility>](../header/utility "cpp/header/utility")` | | | | --- | --- | --- | | ``` template<class T> typename std::add_rvalue_reference<T>::type declval() noexcept; ``` | | (since C++11) | Converts any type `T` to a reference type, making it possible to use member functions in `decltype` expressions without the need to go through constructors. `declval` is commonly used in templates where acceptable template parameters may have no constructor in common, but have the same member function whose return type is needed. Note that `declval` can only be used in [unevaluated contexts](../language/expressions#Unevaluated_expressions "cpp/language/expressions") and is not required to be defined; it is an error to evaluate an expression that contains this function. Formally, the program is ill-formed if this function is [odr-used](../language/definition#ODR-use "cpp/language/definition"). ### Parameters (none). ### Return value Cannot be called and thus never returns a value. The return type is `T&&` unless `T` is (possibly cv-qualified) `void`, in which case the return type is `T`. ### Possible implementation | | | --- | | ``` template<typename T> constexpr bool always_false = false; template<typename T> typename std::add_rvalue_reference<T>::type declval() noexcept { static_assert(always_false<T>, "declval not allowed in an evaluated context"); } ``` | ### Example ``` #include <utility> #include <iostream> struct Default { int foo() const { return 1; } }; struct NonDefault { NonDefault() = delete; int foo() const { return 1; } }; int main() { decltype(Default().foo()) n1 = 1; // type of n1 is int // decltype(NonDefault().foo()) n2 = n1; // error: no default constructor decltype(std::declval<NonDefault>().foo()) n2 = n1; // type of n2 is int std::cout << "n1 = " << n1 << '\n' << "n2 = " << n2 << '\n'; } ``` Output: ``` n1 = 1 n2 = 1 ``` ### See also | | | | --- | --- | | [`decltype` specifier](../language/decltype "cpp/language/decltype")(C++11) | obtains the type of an expression or an entity | | [result\_ofinvoke\_result](../types/result_of "cpp/types/result of") (C++11)(removed in C++20)(C++17) | deduces the result type of invoking a callable object with a set of arguments (class template) | cpp std::any std::any ======== | Defined in header `[<any>](../header/any "cpp/header/any")` | | | | --- | --- | --- | | ``` class any; ``` | | (since C++17) | The class `any` describes a type-safe container for single values of any [copy constructible](../types/is_copy_constructible "cpp/types/is copy constructible") type. 1) An object of class `any` stores an instance of any type that satisfies the constructor requirements or is empty, and this is referred to as the *state* of the class `any` object. The stored instance is called the contained object. Two states are equivalent if they are either both empty or if both are not empty and if the contained objects are equivalent. 2) The non-member `any_cast` functions provide type-safe access to the contained object. Implementations are encouraged to avoid dynamic allocations for small objects, but such an optimization may only be applied to types for which `[std::is\_nothrow\_move\_constructible](../types/is_move_constructible "cpp/types/is move constructible")` returns `true`. ### Member functions | | | | --- | --- | | [(constructor)](any/any "cpp/utility/any/any") | constructs an `any` object (public member function) | | [operator=](any/operator= "cpp/utility/any/operator=") | assigns an `any` object (public member function) | | [(destructor)](any/~any "cpp/utility/any/~any") | destroys an `any` object (public member function) | | Modifiers | | [emplace](any/emplace "cpp/utility/any/emplace") | change the contained object, constructing the new object directly (public member function) | | [reset](any/reset "cpp/utility/any/reset") | destroys contained object (public member function) | | [swap](any/swap "cpp/utility/any/swap") | swaps two `any` objects (public member function) | | Observers | | [has\_value](any/has_value "cpp/utility/any/has value") | checks if object holds a value (public member function) | | [type](any/type "cpp/utility/any/type") | returns the `typeid` of the contained value (public member function) | ### Non-member functions | | | | --- | --- | | [std::swap(std::any)](any/swap2 "cpp/utility/any/swap2") (C++17) | specializes the `[std::swap](../algorithm/swap "cpp/algorithm/swap")` algorithm (function) | | [any\_cast](any/any_cast "cpp/utility/any/any cast") (C++17) | type-safe access to the contained object (function template) | | [make\_any](any/make_any "cpp/utility/any/make any") (C++17) | creates an `any` object (function template) | ### Helper classes | | | | --- | --- | | [bad\_any\_cast](any/bad_any_cast "cpp/utility/any/bad any cast") (C++17) | exception thrown by the value-returning forms of `any_cast` on a type mismatch (class) | ### Notes | [Feature-test](feature_test "cpp/utility/feature test") macro | | --- | | [`__cpp_lib_any`](../feature_test#Library_features "cpp/feature test") | ### Example ``` #include <any> #include <iostream> int main() { std::cout << std::boolalpha; // any type std::any a = 1; std::cout << a.type().name() << ": " << std::any_cast<int>(a) << '\n'; a = 3.14; std::cout << a.type().name() << ": " << std::any_cast<double>(a) << '\n'; a = true; std::cout << a.type().name() << ": " << std::any_cast<bool>(a) << '\n'; // bad cast try { a = 1; std::cout << std::any_cast<float>(a) << '\n'; } catch (const std::bad_any_cast& e) { std::cout << e.what() << '\n'; } // has value a = 2; if (a.has_value()) { std::cout << a.type().name() << ": " << std::any_cast<int>(a) << '\n'; } // reset a.reset(); if (!a.has_value()) { std::cout << "no value\n"; } // pointer to contained data a = 3; int* i = std::any_cast<int>(&a); std::cout << *i << "\n"; } ``` Possible output: ``` int: 1 double: 3.14 bool: true bad any_cast int: 2 no value 3 ``` ### See also | | | | --- | --- | | [function](functional/function "cpp/utility/functional/function") (C++11) | wraps callable object of any copy constructible type with specified function call signature (class template) | | [move\_only\_function](functional/move_only_function "cpp/utility/functional/move only function") (C++23) | wraps callable object of any type with specified function call signature (class template) | | [variant](variant "cpp/utility/variant") (C++17) | a type-safe discriminated union (class template) | | [optional](optional "cpp/utility/optional") (C++17) | a wrapper that may or may not hold an object (class template) | cpp Formatting library (since C++20) Formatting library (since C++20) ================================ The text formatting library offers a safe and extensible alternative to the printf family of functions. It is intended to complement the existing C++ I/O streams library. ### Formatting functions | Defined in header `[<format>](../header/format "cpp/header/format")` | | --- | | [format](format/format "cpp/utility/format/format") (C++20) | stores formatted representation of the arguments in a new string (function template) | | [format\_to](format/format_to "cpp/utility/format/format to") (C++20) | writes out formatted representation of its arguments through an output iterator (function template) | | [format\_to\_n](format/format_to_n "cpp/utility/format/format to n") (C++20) | writes out formatted representation of its arguments through an output iterator, not exceeding specified size (function template) | | [formatted\_size](format/formatted_size "cpp/utility/format/formatted size") (C++20) | determines the number of characters necessary to store the formatted representation of its arguments (function template) | ### Extensibility support and implementation detail | Defined in header `[<format>](../header/format "cpp/header/format")` | | --- | | [vformat](format/vformat "cpp/utility/format/vformat") (C++20) | non-template variant of `[std::format](format/format "cpp/utility/format/format")` using type-erased argument representation (function) | | [vformat\_to](format/vformat_to "cpp/utility/format/vformat to") (C++20) | non-template variant of `[std::format\_to](format/format_to "cpp/utility/format/format to")` using type-erased argument representation (function template) | | [make\_format\_argsmake\_wformat\_args](format/make_format_args "cpp/utility/format/make format args") (C++20)(C++20) | creates a type-erased object referencing all formatting arguments, convertible to format\_args (function template) | | [visit\_format\_arg](format/visit_format_arg "cpp/utility/format/visit format arg") (C++20) | argument visitation interface for user-defined formatters (function template) | | [formatter](format/formatter "cpp/utility/format/formatter") (C++20) | class template that defines formatting rules for a given type (class template) | | [basic\_format\_arg](format/basic_format_arg "cpp/utility/format/basic format arg") (C++20) | class template that provides access to a formatting argument for user-defined formatters (class template) | | [basic\_format\_argsformat\_argswformat\_args](format/basic_format_args "cpp/utility/format/basic format args") (C++20)(C++20)(C++20) | class that provides access to all formatting arguments (class template) | | [basic\_format\_stringformat\_stringwformat\_string](format/basic_format_string "cpp/utility/format/basic format string") (C++20)(C++20)(C++20) | class template that performs compile-time format string checks at construction time (class template) | | [basic\_format\_contextformat\_contextwformat\_context](format/basic_format_context "cpp/utility/format/basic format context") (C++20)(C++20)(C++20) | formatting state, including all formatting arguments and the output iterator (class template) | | [basic\_format\_parse\_contextformat\_parse\_contextwformat\_parse\_context](format/basic_format_parse_context "cpp/utility/format/basic format parse context") (C++20)(C++20)(C++20) | formatting string parser state (class template) | | [format\_error](format/format_error "cpp/utility/format/format error") (C++20) | exception type thrown on formatting errors (class) | ### Notes | [Feature-test](feature_test "cpp/utility/feature test") macro | Value | Std | Comment | | --- | --- | --- | --- | | [`__cpp_lib_format`](../feature_test#Library_features "cpp/feature test") | `201907L` | (C++20) | | [`__cpp_lib_format`](../feature_test#Library_features "cpp/feature test") | `202106L` | (C++20)(DR) | Compile-time format string checks;Reducing parameterization of `[std::vformat\_to](format/vformat_to "cpp/utility/format/vformat to")` | | [`__cpp_lib_format`](../feature_test#Library_features "cpp/feature test") | `202110L` | (C++20)(DR) | Fixing locale handling in chrono formatters; Supporting non-const-formattable types | | [`__cpp_lib_format`](../feature_test#Library_features "cpp/feature test") | `202207L` | (C++23) | Exposing `std::basic_format_string`; clarify handling of encodings in localized formatting of chrono types | | [`__cpp_lib_format_ranges`](../feature_test#Library_features "cpp/feature test") | `202207L` | (C++23) | ### Example ``` #include <format> #include <cassert> int main() { std::string message = std::format("The answer is {}.", 42); assert( message == "The answer is 42." ); } ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [P2418R2](https://wg21.link/P2418R2) | C++20 | objects that are neither const-formattable nor copyable(such as generator-like objects) are not formattable | allow formatting these objects(relaxed formatter requirements) | | [P2508R1](https://wg21.link/P2508R1) | C++20 | there's no user-visible name for this facility | the name `basic_format_string` is exposed |
programming_docs
cpp std::bitset std::bitset =========== | Defined in header `[<bitset>](../header/bitset "cpp/header/bitset")` | | | | --- | --- | --- | | ``` template< std::size_t N > class bitset; ``` | | | The class template `bitset` represents a fixed-size sequence of `N` bits. Bitsets can be manipulated by standard logic operators and converted to and from strings and integers. For the purpose of the string representation and of naming directions for shift operations, the sequence is thought of as having its lowest indexed elements at the *right*, as in the binary representation of integers. `bitset` meets the requirements of [CopyConstructible](../named_req/copyconstructible "cpp/named req/CopyConstructible") and [CopyAssignable](../named_req/copyassignable "cpp/named req/CopyAssignable"). | | | | --- | --- | | All member functions of `std::bitset` are `constexpr`: it is possible to create and use `std::bitset` objects in the evaluation of a constant expression. | (since C++23) | ### Template parameters | | | | | --- | --- | --- | | N | - | the number of bits to allocate storage for | ### Member types | | | | --- | --- | | [reference](bitset/reference "cpp/utility/bitset/reference") | proxy class representing a reference to a bit (class) | ### Member functions | | | | --- | --- | | [(constructor)](bitset/bitset "cpp/utility/bitset/bitset") | constructs the bitset (public member function) | | [operator==operator!=](bitset/operator_cmp "cpp/utility/bitset/operator cmp") (removed in C++20) | compares the contents (public member function) | | Element access | | [operator[]](bitset/operator_at "cpp/utility/bitset/operator at") | accesses specific bit (public member function) | | [test](bitset/test "cpp/utility/bitset/test") | accesses specific bit (public member function) | | [allanynone](bitset/all_any_none "cpp/utility/bitset/all any none") (C++11) | checks if all, any or none of the bits are set to `true` (public member function) | | [count](bitset/count "cpp/utility/bitset/count") | returns the number of bits set to `true` (public member function) | | Capacity | | [size](bitset/size "cpp/utility/bitset/size") | returns the number of bits that the bitset holds (public member function) | | Modifiers | | [operator&=operator|=operator^=operator~](bitset/operator_logic "cpp/utility/bitset/operator logic") | performs binary AND, OR, XOR and NOT (public member function) | | [operator<<=operator>>=operator<<operator>>](bitset/operator_ltltgtgt "cpp/utility/bitset/operator ltltgtgt") | performs binary shift left and shift right (public member function) | | [set](bitset/set "cpp/utility/bitset/set") | sets bits to `true` or given value (public member function) | | [reset](bitset/reset "cpp/utility/bitset/reset") | sets bits to `false` (public member function) | | [flip](bitset/flip "cpp/utility/bitset/flip") | toggles the values of bits (public member function) | | Conversions | | [to\_string](bitset/to_string "cpp/utility/bitset/to string") | returns a string representation of the data (public member function) | | [to\_ulong](bitset/to_ulong "cpp/utility/bitset/to ulong") | returns an `unsigned long` integer representation of the data (public member function) | | [to\_ullong](bitset/to_ullong "cpp/utility/bitset/to ullong") (C++11) | returns an `unsigned long long` integer representation of the data (public member function) | ### Non-member functions | | | | --- | --- | | [operator&operator|operator^](bitset/operator_logic2 "cpp/utility/bitset/operator logic2") | performs binary logic operations on bitsets (function template) | | [operator<<operator>>](bitset/operator_ltltgtgt2 "cpp/utility/bitset/operator ltltgtgt2") | performs stream input and output of bitsets (function template) | ### Helper classes | | | | --- | --- | | [std::hash<std::bitset>](bitset/hash "cpp/utility/bitset/hash") (C++11) | hash support for `std::bitset` (class template specialization) | ### Notes If the size of a bit-set is not known at compile time, or it is necessary to change its size at run-time, the dynamic types such as [`std::vector<bool>`](../container/vector_bool "cpp/container/vector bool") or [`boost::dynamic_bitset<>`](https://www.boost.org/doc/libs/release/libs/dynamic_bitset/dynamic_bitset.html) may be used instead. | [Feature-test](feature_test "cpp/utility/feature test") macro | Value | Std | | --- | --- | --- | | [`__cpp_lib_constexpr_bitset`](../feature_test#Library_features "cpp/feature test") | `202202L` | (C++23) | ### Example ``` #include <bitset> #include <cstddef> #include <cassert> #include <iostream> int main() { typedef std::size_t length_t, position_t; // the hints // constructors: constexpr std::bitset<4> b1; constexpr std::bitset<4> b2{0xA}; // == 0B1010 std::bitset<4> b3{"0011"}; // can also be constexpr since C++23 std::bitset<8> b4{"ABBA", length_t(4), /*0:*/'A', /*1:*/'B'}; // == 0B0000'0110 // bitsets can be printed out to a stream: std::cout << "b1:" << b1 << "; b2:" << b2 << "; b3:" << b3 << "; b4:" << b4 << '\n'; // bitset supports bitwise operations: b3 |= 0b0100; assert(b3 == 0b0111); b3 &= 0b0011; assert(b3 == 0b0011); b3 ^= std::bitset<4>{0b1100}; assert(b3 == 0b1111); // operations on the whole set: b3.reset(); assert(b3 == 0); b3.set(); assert(b3 == 0b1111); assert(b3.all() && b3.any() && !b3.none()); b3.flip(); assert(b3 == 0); // operations on individual bits: b3.set(position_t(1), true); assert(b3 == 0b0010); b3.set(position_t(1), false); assert(b3 == 0); b3.flip(position_t(2)); assert(b3 == 0b0100); b3.reset(position_t(2)); assert(b3 == 0); // subscript operator[] is supported: b3[2] = true; assert(true == b3[2]); // other operations: assert(b3.count() == 1); assert(b3.size() == 4); assert(b3.to_ullong() == 0b0100ULL); assert(b3.to_string() == "0100"); } ``` Output: ``` b1:0000; b2:1010; b3:0011; b4:00000110 ``` ### See also | | | | --- | --- | | [vector<bool>](../container/vector_bool "cpp/container/vector bool") | space-efficient dynamic bitset (class template specialization) | | [**Bit manipulation**](../numeric#Bit_manipulation_.28since_C.2B.2B20.29 "cpp/numeric") (C++20) | utilities to access, manipulate, and process individual bits and bit sequences | cpp std::tuple_element std::tuple\_element =================== | Defined in header `[<tuple>](../header/tuple "cpp/header/tuple")` | | | | --- | --- | --- | | Defined in header `[<array>](../header/array "cpp/header/array")` | | | | Defined in header `[<utility>](../header/utility "cpp/header/utility")` | | | | Defined in header `[<ranges>](../header/ranges "cpp/header/ranges")` | | (since C++20) | | ``` template< std::size_t I, class T > struct tuple_element; // not defined ``` | (1) | (since C++11) | | ``` template< std::size_t I, class T > struct tuple_element< I, const T > { using type = typename std::add_const<typename std::tuple_element<I, T>::type>::type; }; ``` | (2) | (since C++11) | | ``` template< std::size_t I, class T > struct tuple_element< I, volatile T > { using type = typename std::add_volatile<typename std::tuple_element<I, T>::type>::type; }; ``` | (3) | (since C++11) (deprecated in C++20) | | ``` template< std::size_t I, class T > struct tuple_element< I, const volatile T > { using type = typename std::add_cv<typename std::tuple_element<I, T>::type>::type; }; ``` | (4) | (since C++11) (deprecated in C++20) | Provides compile-time indexed access to the types of the elements of a tuple-like type. 1) The primary template is not defined. An explicit (full) or partial specialization is required to make a type tuple-like. 2-4) Specializations for cv-qualified types simply add corresponding cv-qualifiers by default. | | | | --- | --- | | `std::tuple_element` interacts with the core language: it can provide [structured binding](../language/structured_binding "cpp/language/structured binding") support in the tuple-like case. | (since C++17) | ### Specializations The standard library provides following specializations for standard library types: | | | | --- | --- | | [std::tuple\_element<std::tuple>](tuple/tuple_element "cpp/utility/tuple/tuple element") (C++11) | obtains the type of the specified element (class template specialization) | | [std::tuple\_element<std::pair>](pair/tuple_element "cpp/utility/pair/tuple element") (C++11) | obtains the type of the elements of `pair` (class template specialization) | | [std::tuple\_element<std::array>](../container/array/tuple_element "cpp/container/array/tuple element") (C++11) | obtains the type of the elements of `array` (class template specialization) | | [std::tuple\_element<std::ranges::subrange>](../ranges/subrange/tuple_element "cpp/ranges/subrange/tuple element") (C++20) | obtains the type of the iterator or the sentinel of a `[std::ranges::subrange](../ranges/subrange "cpp/ranges/subrange")` (class template specialization) | Users may specialize `std::tuple_element` for program-defined types to make them tuple-like. In normal cases where the `get` functions returns reference members or reference to subobjects, only specializations for cv-unqualified types are needed to be customized. ### Member types | Member type | Definition | | --- | --- | | type | for a standard specialization, the type of `I`th element of the tuple-like type `T`, where `I` is in [0, `[std::tuple\_size](http://en.cppreference.com/w/cpp/utility/tuple/tuple_size)<T>::value`) | ### Helper types | Defined in header `[<tuple>](../header/tuple "cpp/header/tuple")` | | | | --- | --- | --- | | ``` template <std::size_t I, class T> using tuple_element_t = typename tuple_element<I, T>::type; ``` | | (since C++14) | ### Notes | [Feature-test](feature_test "cpp/utility/feature test") macro | | --- | | [`__cpp_lib_tuple_element_t`](../feature_test#Library_features "cpp/feature test") | ### Example ``` #include <array> #include <cstddef> #include <iostream> #include <ranges> #include <tuple> #include <type_traits> #include <utility> template <typename T1, typename T2, typename T3> struct Triple { T1 t1; T2 t2; T3 t3; }; // A specialization of std::tuple_element for program-defined type Triple: template <std::size_t I, typename T1, typename T2, typename T3> struct std::tuple_element<I, Triple<T1, T2, T3>> { static_assert(I < 4); }; template <typename T1, typename T2, typename T3> struct std::tuple_element<0, Triple<T1, T2, T3>> { using type = T1; }; template <typename T1, typename T2, typename T3> struct std::tuple_element<1, Triple<T1, T2, T3>> { using type = T2; }; template <typename T1, typename T2, typename T3> struct std::tuple_element<2, Triple<T1, T2, T3>> { using type = T3; }; template <typename... Args> struct TripleTypes { static_assert(3 == sizeof...(Args), "Expected exactly 3 type names!"); template <std::size_t N> using type = typename std::tuple_element_t<N, Triple<Args...>>; }; int main() { TripleTypes<char, int, float>::type<1> i{42}; std::cout << i << '\n'; using Tri = Triple<int, char, short>; //< Program-defined type static_assert(std::is_same_v<std::tuple_element_t<0, Tri>, int> && std::is_same_v<std::tuple_element_t<1, Tri>, char> && std::is_same_v<std::tuple_element_t<2, Tri>, short>); using Tuple = std::tuple<int, char, short>; static_assert(std::is_same_v<std::tuple_element_t<0, Tuple>, int> && std::is_same_v<std::tuple_element_t<1, Tuple>, char> && std::is_same_v<std::tuple_element_t<2, Tuple>, short>); using Array3 = std::array<int, 3>; static_assert(std::is_same_v<std::tuple_element_t<0, Array3>, int> && std::is_same_v<std::tuple_element_t<1, Array3>, int> && std::is_same_v<std::tuple_element_t<2, Array3>, int>); using Pair = std::pair<Tuple, Tri>; static_assert(std::is_same_v<std::tuple_element_t<0, Pair>, Tuple> && std::is_same_v<std::tuple_element_t<1, Pair>, Tri>); using Sub = std::ranges::subrange<int*, int*>; static_assert(std::is_same_v<std::tuple_element_t<0, Sub>, int*> && std::is_same_v<std::tuple_element_t<1, Sub>, int*>); } ``` Output: ``` 42 ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 2212](https://cplusplus.github.io/LWG/issue2212) | C++11 | specializations for cv types were not required in some headers, which led to ambiguity | required | ### See also | | | | --- | --- | | [Structured binding](../language/structured_binding "cpp/language/structured binding") (C++17) | binds the specified names to sub-objects or tuple elements of the initializer | | [tuple\_size](tuple_size "cpp/utility/tuple size") (C++11) | obtains the number of elements of a tuple-like type (class template) | | [tuple\_cat](tuple/tuple_cat "cpp/utility/tuple/tuple cat") (C++11) | creates a `tuple` by concatenating any number of tuples (function template) | cpp std::variant std::variant ============ | Defined in header `[<variant>](../header/variant "cpp/header/variant")` | | | | --- | --- | --- | | ``` template <class... Types> class variant; ``` | | (since C++17) | The class template `std::variant` represents a type-safe [union](../language/union "cpp/language/union"). An instance of `std::variant` at any given time either holds a value of one of its alternative types, or in the case of error - no value (this state is hard to achieve, see [`valueless_by_exception`](variant/valueless_by_exception "cpp/utility/variant/valueless by exception")). As with unions, if a variant holds a value of some object type `T`, the object representation of `T` is allocated directly within the object representation of the variant itself. Variant is not allowed to allocate additional (dynamic) memory. A variant is not permitted to hold references, arrays, or the type `void`. Empty variants are also ill-formed (`std::variant<[std::monostate](http://en.cppreference.com/w/cpp/utility/variant/monostate)>` can be used instead). A variant is permitted to hold the same type more than once, and to hold differently cv-qualified versions of the same type. Consistent with the behavior of unions during [aggregate initialization](../language/aggregate_initialization "cpp/language/aggregate initialization"), a default-constructed variant holds a value of its first alternative, unless that alternative is not default-constructible (in which case the variant is not default-constructible either). The helper class [`std::monostate`](variant/monostate "cpp/utility/variant/monostate") can be used to make such variants default-constructible. ### Template parameters | | | | | --- | --- | --- | | Types | - | the types that may be stored in this variant. All types must meet the [Destructible](../named_req/destructible "cpp/named req/Destructible") requirements (in particular, array types and non-object types are not allowed). | ### Member functions | | | | --- | --- | | [(constructor)](variant/variant "cpp/utility/variant/variant") | constructs the variant object (public member function) | | [(destructor)](variant/~variant "cpp/utility/variant/~variant") | destroys the variant, along with its contained value (public member function) | | [operator=](variant/operator= "cpp/utility/variant/operator=") | assigns a variant (public member function) | | Observers | | [index](variant/index "cpp/utility/variant/index") | returns the zero-based index of the alternative held by the variant (public member function) | | [valueless\_by\_exception](variant/valueless_by_exception "cpp/utility/variant/valueless by exception") | checks if the variant is in the invalid state (public member function) | | Modifiers | | [emplace](variant/emplace "cpp/utility/variant/emplace") | constructs a value in the variant, in place (public member function) | | [swap](variant/swap "cpp/utility/variant/swap") | swaps with another variant (public member function) | ### Non-member functions | | | | --- | --- | | [visit](variant/visit "cpp/utility/variant/visit") (C++17) | calls the provided functor with the arguments held by one or more variants (function template) | | [holds\_alternative](variant/holds_alternative "cpp/utility/variant/holds alternative") (C++17) | checks if a variant currently holds a given type (function template) | | [std::get(std::variant)](variant/get "cpp/utility/variant/get") (C++17) | reads the value of the variant given the index or the type (if the type is unique), throws on error (function template) | | [get\_if](variant/get_if "cpp/utility/variant/get if") (C++17) | obtains a pointer to the value of a pointed-to variant given the index or the type (if unique), returns null on error (function template) | | [operator==operator!=operator<operator<=operator>operator>=operator<=>](variant/operator_cmp "cpp/utility/variant/operator cmp") (C++17)(C++17)(C++17)(C++17)(C++17)(C++17)(C++20) | compares `variant` objects as their contained values (function template) | | [std::swap(std::variant)](variant/swap2 "cpp/utility/variant/swap2") (C++17) | specializes the `[std::swap](../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | ### Helper classes | | | | --- | --- | | [monostate](variant/monostate "cpp/utility/variant/monostate") (C++17) | placeholder type for use as the first alternative in a variant of non-default-constructible types (class) | | [bad\_variant\_access](variant/bad_variant_access "cpp/utility/variant/bad variant access") (C++17) | exception thrown on invalid accesses to the value of a variant (class) | | [variant\_sizevariant\_size\_v](variant/variant_size "cpp/utility/variant/variant size") (C++17) | obtains the size of the variant's list of alternatives at compile time (class template) (variable template) | | [variant\_alternativevariant\_alternative\_t](variant/variant_alternative "cpp/utility/variant/variant alternative") (C++17) | obtains the type of the alternative specified by its index, at compile time (class template) (alias template) | | [std::hash<std::variant>](variant/hash "cpp/utility/variant/hash") (C++17) | specializes the `[std::hash](hash "cpp/utility/hash")` algorithm (class template specialization) | ### Helper objects | | | | --- | --- | | [variant\_npos](variant/variant_npos "cpp/utility/variant/variant npos") (C++17) | index of the variant in the invalid state (constant) | ### Notes | [Feature-test](feature_test "cpp/utility/feature test") macro | | --- | | [`__cpp_lib_variant`](../feature_test#Library_features "cpp/feature test") | ### Example ``` #include <variant> #include <string> #include <cassert> #include <iostream> int main() { std::variant<int, float> v, w; v = 42; // v contains int int i = std::get<int>(v); assert(42 == i); // succeeds w = std::get<int>(v); w = std::get<0>(v); // same effect as the previous line w = v; // same effect as the previous line // std::get<double>(v); // error: no double in [int, float] // std::get<3>(v); // error: valid index values are 0 and 1 try { std::get<float>(w); // w contains int, not float: will throw } catch (const std::bad_variant_access& ex) { std::cout << ex.what() << '\n'; } using namespace std::literals; std::variant<std::string> x("abc"); // converting constructors work when unambiguous x = "def"; // converting assignment also works when unambiguous std::variant<std::string, void const*> y("abc"); // casts to void const * when passed a char const * assert(std::holds_alternative<void const*>(y)); // succeeds y = "xyz"s; assert(std::holds_alternative<std::string>(y)); // succeeds } ``` Possible output: ``` std::get: wrong index for variant ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 2901](https://cplusplus.github.io/LWG/issue2901) | C++17 | specialization of `[std::uses\_allocator](../memory/uses_allocator "cpp/memory/uses allocator")` provided, but `variant` can't properly support allocators | specialization removed | ### See also | | | | --- | --- | | [in\_place in\_place\_type in\_place\_index in\_place\_t in\_place\_type\_t in\_place\_index\_t](in_place "cpp/utility/in place") (C++17) | in-place construction tag (class template) | | [optional](optional "cpp/utility/optional") (C++17) | a wrapper that may or may not hold an object (class template) | | [any](any "cpp/utility/any") (C++17) | Objects that hold instances of any [CopyConstructible](../named_req/copyconstructible "cpp/named req/CopyConstructible") type. (class) |
programming_docs
cpp Library feature-test macros (since C++20) Library feature-test macros (since C++20) ========================================= Each of following macros is defined if the header [`<version>`](../header/version "cpp/header/version") or one of the corresponding headers specified in the table is included. | Macro name | Value | Header | | --- | --- | --- | | `__cpp_lib_addressof_constexpr` | 201603L | [`<memory>`](../header/memory "cpp/header/memory") | | `__cpp_lib_algorithm_iterator_requirements` | 202207L | [`<algorithm>`](../header/algorithm "cpp/header/algorithm") [`<numeric>`](../header/numeric "cpp/header/numeric") [`<memory>`](../header/memory "cpp/header/memory") | | `__cpp_lib_allocate_at_least` | 202106L | [`<memory>`](../header/memory "cpp/header/memory") | | `__cpp_lib_allocator_traits_is_always_equal` | 201411L | [`<memory>`](../header/memory "cpp/header/memory") [`<scoped_allocator>`](../header/scoped_allocator "cpp/header/scoped allocator") [`<string>`](../header/string "cpp/header/string") [`<deque>`](../header/deque "cpp/header/deque") [`<forward_list>`](../header/forward_list "cpp/header/forward list") [`<list>`](../header/list "cpp/header/list") [`<vector>`](../header/vector "cpp/header/vector") [`<map>`](../header/map "cpp/header/map") [`<set>`](../header/set "cpp/header/set") [`<unordered_map>`](../header/unordered_map "cpp/header/unordered map") [`<unordered_set>`](../header/unordered_set "cpp/header/unordered set") | | `__cpp_lib_adaptor_iterator_pair_constructor` | 202106L | [`<stack>`](../header/stack "cpp/header/stack") [`<queue>`](../header/queue "cpp/header/queue") | | `__cpp_lib_any` | 201606L | [`<any>`](../header/any "cpp/header/any") | | `__cpp_lib_apply` | 201603L | [`<tuple>`](../header/tuple "cpp/header/tuple") | | `__cpp_lib_array_constexpr` | 201811L | [`<iterator>`](../header/iterator "cpp/header/iterator") [`<array>`](../header/array "cpp/header/array") | | `__cpp_lib_as_const` | 201510L | [`<utility>`](../header/utility "cpp/header/utility") | | `__cpp_lib_associative_heterogeneous_erasure` | 202110L | [`<map>`](../header/map "cpp/header/map") [`<set>`](../header/set "cpp/header/set") [`<unordered_map>`](../header/unordered_map "cpp/header/unordered map") [`<unordered_set>`](../header/unordered_set "cpp/header/unordered set") | | `__cpp_lib_assume_aligned` | 201811L | [`<memory>`](../header/memory "cpp/header/memory") | | `__cpp_lib_atomic_flag_test` | 201907L | [`<atomic>`](../header/atomic "cpp/header/atomic") | | `__cpp_lib_atomic_float` | 201711L | [`<atomic>`](../header/atomic "cpp/header/atomic") | | `__cpp_lib_atomic_is_always_lock_free` | 201603L | [`<atomic>`](../header/atomic "cpp/header/atomic") | | `__cpp_lib_atomic_lock_free_type_aliases` | 201907L | [`<atomic>`](../header/atomic "cpp/header/atomic") | | `__cpp_lib_atomic_ref` | 201806L | [`<atomic>`](../header/atomic "cpp/header/atomic") | | `__cpp_lib_atomic_shared_ptr` | 201711L | [`<memory>`](../header/memory "cpp/header/memory") | | `__cpp_lib_atomic_value_initialization` | 201911L | [`<atomic>`](../header/atomic "cpp/header/atomic") [`<memory>`](../header/memory "cpp/header/memory") | | `__cpp_lib_atomic_wait` | 201907L | [`<atomic>`](../header/atomic "cpp/header/atomic") | | `__cpp_lib_barrier` | 201907L | [`<barrier>`](../header/barrier "cpp/header/barrier") | | `__cpp_lib_bind_back` | 202202L | [`<functional>`](../header/functional "cpp/header/functional") | | `__cpp_lib_bind_front` | 201907L | [`<functional>`](../header/functional "cpp/header/functional") | | `__cpp_lib_bit_cast` | 201806L | [`<bit>`](../header/bit "cpp/header/bit") | | `__cpp_lib_bitops` | 201907L | [`<bit>`](../header/bit "cpp/header/bit") | | `__cpp_lib_bool_constant` | 201505L | [`<type_traits>`](../header/type_traits "cpp/header/type traits") | | `__cpp_lib_bounded_array_traits` | 201902L | [`<type_traits>`](../header/type_traits "cpp/header/type traits") | | `__cpp_lib_boyer_moore_searcher` | 201603L | [`<functional>`](../header/functional "cpp/header/functional") | | `__cpp_lib_byte` | 201603L | [`<cstddef>`](../header/cstddef "cpp/header/cstddef") | | `__cpp_lib_byteswap` | 202110L | [`<bit>`](../header/bit "cpp/header/bit") | | `__cpp_lib_char8_t` | 201907L | [`<atomic>`](../header/atomic "cpp/header/atomic") [`<filesystem>`](../header/filesystem "cpp/header/filesystem") [`<istream>`](../header/istream "cpp/header/istream") [`<limits>`](../header/limits "cpp/header/limits") [`<locale>`](../header/locale "cpp/header/locale") [`<ostream>`](../header/ostream "cpp/header/ostream") [`<string>`](../header/string "cpp/header/string") [`<string_view>`](../header/string_view "cpp/header/string view") | | `__cpp_lib_chrono` | 201907L | [`<chrono>`](../header/chrono "cpp/header/chrono") | | `__cpp_lib_chrono_udls` | 201304L | [`<chrono>`](../header/chrono "cpp/header/chrono") | | `__cpp_lib_clamp` | 201603L | [`<algorithm>`](../header/algorithm "cpp/header/algorithm") | | `__cpp_lib_complex_udls` | 201309L | [`<complex>`](../header/complex "cpp/header/complex") | | `__cpp_lib_concepts` | 202207L | [`<concepts>`](../header/concepts "cpp/header/concepts") [`<compare>`](../header/compare "cpp/header/compare") | | `__cpp_lib_constexpr_algorithms` | 201806L | [`<algorithm>`](../header/algorithm "cpp/header/algorithm") | | `__cpp_lib_constexpr_bitset` | 202202L | [`<bitset>`](../header/bitset "cpp/header/bitset") | | `__cpp_lib_constexpr_charconv` | 202207L | [`<charconv>`](../header/charconv "cpp/header/charconv") | | `__cpp_lib_constexpr_cmath` | 202202L | [`<cmath>`](../header/cmath "cpp/header/cmath") [`<cstdlib>`](../header/cstdlib "cpp/header/cstdlib") | | `__cpp_lib_constexpr_complex` | 201711L | [`<complex>`](../header/complex "cpp/header/complex") | | `__cpp_lib_constexpr_dynamic_alloc` | 201907L | [`<memory>`](../header/memory "cpp/header/memory") | | `__cpp_lib_constexpr_functional` | 201907L | [`<functional>`](../header/functional "cpp/header/functional") | | `__cpp_lib_constexpr_iterator` | 201811L | [`<iterator>`](../header/iterator "cpp/header/iterator") | | `__cpp_lib_constexpr_memory` | 202202L | [`<memory>`](../header/memory "cpp/header/memory") | | `__cpp_lib_constexpr_numeric` | 201911L | [`<numeric>`](../header/numeric "cpp/header/numeric") | | `__cpp_lib_constexpr_string` | 201907L | [`<string>`](../header/string "cpp/header/string") | | `__cpp_lib_constexpr_string_view` | 201811L | [`<string_view>`](../header/string_view "cpp/header/string view") | | `__cpp_lib_constexpr_tuple` | 201811L | [`<tuple>`](../header/tuple "cpp/header/tuple") | | `__cpp_lib_constexpr_typeinfo` | 202106L | [`<typeinfo>`](../header/typeinfo "cpp/header/typeinfo") | | `__cpp_lib_constexpr_utility` | 201811L | [`<utility>`](../header/utility "cpp/header/utility") | | `__cpp_lib_constexpr_vector` | 201907L | [`<vector>`](../header/vector "cpp/header/vector") | | `__cpp_lib_containers_ranges` | 202202L | [`<vector>`](../header/vector "cpp/header/vector") [`<list>`](../header/list "cpp/header/list") [`<forward_list>`](../header/forward_list "cpp/header/forward list") [`<map>`](../header/map "cpp/header/map") [`<set>`](../header/set "cpp/header/set") [`<unordered_map>`](../header/unordered_map "cpp/header/unordered map") [`<unordered_set>`](../header/unordered_set "cpp/header/unordered set") [`<deque>`](../header/deque "cpp/header/deque") [`<queue>`](../header/queue "cpp/header/queue") [`<stack>`](../header/stack "cpp/header/stack") [`<string>`](../header/string "cpp/header/string") | | `__cpp_lib_coroutine` | 201902L | [`<coroutine>`](../header/coroutine "cpp/header/coroutine") | | `__cpp_lib_destroying_delete` | 201806L | [`<new>`](../header/new "cpp/header/new") | | `__cpp_lib_enable_shared_from_this` | 201603L | [`<memory>`](../header/memory "cpp/header/memory") | | `__cpp_lib_endian` | 201907L | [`<bit>`](../header/bit "cpp/header/bit") | | `__cpp_lib_erase_if` | 202002L | [`<string>`](../header/string "cpp/header/string") [`<deque>`](../header/deque "cpp/header/deque") [`<forward_list>`](../header/forward_list "cpp/header/forward list") [`<list>`](../header/list "cpp/header/list") [`<vector>`](../header/vector "cpp/header/vector") [`<map>`](../header/map "cpp/header/map") [`<set>`](../header/set "cpp/header/set") [`<unordered_map>`](../header/unordered_map "cpp/header/unordered map") [`<unordered_set>`](../header/unordered_set "cpp/header/unordered set") | | `__cpp_lib_exchange_function` | 201304L | [`<utility>`](../header/utility "cpp/header/utility") | | `__cpp_lib_execution` | 201902L | [`<execution>`](../header/execution "cpp/header/execution") | | `__cpp_lib_expected` | 202202L | [`<expected>`](../header/expected "cpp/header/expected") | | `__cpp_lib_filesystem` | 201703L | [`<filesystem>`](../header/filesystem "cpp/header/filesystem") | | `__cpp_lib_find_last` | 202207L | [`<algorithm>`](../header/algorithm "cpp/header/algorithm") | | `__cpp_lib_flat_map` | 202207L | [`<flat_map>`](../header/flat_map "cpp/header/flat map") | | `__cpp_lib_format` | 202207L | [`<format>`](../header/format "cpp/header/format") | | `__cpp_lib_forward_like` | 202207L | [`<utility>`](../header/utility "cpp/header/utility") | | `__cpp_lib_gcd_lcm` | 201606L | [`<numeric>`](../header/numeric "cpp/header/numeric") | | `__cpp_lib_generator` | 202207L | [`<generator>`](../header/generator "cpp/header/generator") | | `__cpp_lib_generic_associative_lookup` | 201304L | [`<map>`](../header/map "cpp/header/map") [`<set>`](../header/set "cpp/header/set") | | `__cpp_lib_generic_unordered_lookup` | 201811L | [`<unordered_map>`](../header/unordered_map "cpp/header/unordered map") [`<unordered_set>`](../header/unordered_set "cpp/header/unordered set") | | `__cpp_lib_hardware_interference_size` | 201703L | [`<new>`](../header/new "cpp/header/new") | | `__cpp_lib_has_unique_object_representations` | 201606L | [`<type_traits>`](../header/type_traits "cpp/header/type traits") | | `__cpp_lib_hypot` | 201603L | [`<cmath>`](../header/cmath "cpp/header/cmath") | | `__cpp_lib_incomplete_container_elements` | 201505L | [`<forward_list>`](../header/forward_list "cpp/header/forward list") [`<list>`](../header/list "cpp/header/list") [`<vector>`](../header/vector "cpp/header/vector") | | `__cpp_lib_int_pow2` | 202002L | [`<bit>`](../header/bit "cpp/header/bit") | | `__cpp_lib_integer_comparison_functions` | 202002L | [`<utility>`](../header/utility "cpp/header/utility") | | `__cpp_lib_integer_sequence` | 201304L | [`<utility>`](../header/utility "cpp/header/utility") | | `__cpp_lib_integral_constant_callable` | 201304L | [`<type_traits>`](../header/type_traits "cpp/header/type traits") | | `__cpp_lib_interpolate` | 201902L | [`<cmath>`](../header/cmath "cpp/header/cmath") [`<numeric>`](../header/numeric "cpp/header/numeric") | | `__cpp_lib_invoke` | 201411L | [`<functional>`](../header/functional "cpp/header/functional") | | `__cpp_lib_invoke_r` | 202106L | [`<functional>`](../header/functional "cpp/header/functional") | | `__cpp_lib_ios_noreplace` | 202207L | [`<ios>`](../header/ios "cpp/header/ios") | | `__cpp_lib_is_aggregate` | 201703L | [`<type_traits>`](../header/type_traits "cpp/header/type traits") | | `__cpp_lib_is_constant_evaluated` | 201811L | [`<type_traits>`](../header/type_traits "cpp/header/type traits") | | `__cpp_lib_is_final` | 201402L | [`<type_traits>`](../header/type_traits "cpp/header/type traits") | | `__cpp_lib_is_invocable` | 201703L | [`<type_traits>`](../header/type_traits "cpp/header/type traits") | | `__cpp_lib_is_layout_compatible` | 201907L | [`<type_traits>`](../header/type_traits "cpp/header/type traits") | | `__cpp_lib_is_nothrow_convertible` | 201806L | [`<type_traits>`](../header/type_traits "cpp/header/type traits") | | `__cpp_lib_is_null_pointer` | 201309L | [`<type_traits>`](../header/type_traits "cpp/header/type traits") | | `__cpp_lib_is_pointer_interconvertible` | 201907L | [`<type_traits>`](../header/type_traits "cpp/header/type traits") | | `__cpp_lib_is_scoped_enum` | 202011L | [`<type_traits>`](../header/type_traits "cpp/header/type traits") | | `__cpp_lib_is_swappable` | 201603L | [`<type_traits>`](../header/type_traits "cpp/header/type traits") | | `__cpp_lib_jthread` | 201911L | [`<stop_token>`](../header/stop_token "cpp/header/stop token") [`<thread>`](../header/thread "cpp/header/thread") | | `__cpp_lib_latch` | 201907L | [`<latch>`](../header/latch "cpp/header/latch") | | `__cpp_lib_launder` | 201606L | [`<new>`](../header/new "cpp/header/new") | | `__cpp_lib_list_remove_return_type` | 201806L | [`<forward_list>`](../header/forward_list "cpp/header/forward list") [`<list>`](../header/list "cpp/header/list") | | `__cpp_lib_logical_traits` | 201510L | [`<type_traits>`](../header/type_traits "cpp/header/type traits") | | `__cpp_lib_make_from_tuple` | 201606L | [`<tuple>`](../header/tuple "cpp/header/tuple") | | `__cpp_lib_make_reverse_iterator` | 201402L | [`<iterator>`](../header/iterator "cpp/header/iterator") | | `__cpp_lib_make_unique` | 201304L | [`<memory>`](../header/memory "cpp/header/memory") | | `__cpp_lib_map_try_emplace` | 201411L | [`<map>`](../header/map "cpp/header/map") | | `__cpp_lib_math_constants` | 201907L | [`<numbers>`](../header/numbers "cpp/header/numbers") | | `__cpp_lib_math_special_functions` | 201603L | [`<cmath>`](../header/cmath "cpp/header/cmath") | | `__cpp_lib_mdspan` | 202207L | [`<mdspan>`](../header/mdspan "cpp/header/mdspan") | | `__cpp_lib_memory_resource` | 201603L | [`<memory_resource>`](../header/memory_resource "cpp/header/memory resource") | | `__cpp_lib_move_iterator_concept` | 202207L | [`<iterator>`](../header/iterator "cpp/header/iterator") | | `__cpp_lib_move_only_function` | 202110L | [`<functional>`](../header/functional "cpp/header/functional") | | `__cpp_lib_node_extract` | 201606L | [`<map>`](../header/map "cpp/header/map") [`<set>`](../header/set "cpp/header/set") [`<unordered_map>`](../header/unordered_map "cpp/header/unordered map") [`<unordered_set>`](../header/unordered_set "cpp/header/unordered set") | | `__cpp_lib_nonmember_container_access` | 201411L | [`<array>`](../header/array "cpp/header/array") [`<deque>`](../header/deque "cpp/header/deque") [`<forward_list>`](../header/forward_list "cpp/header/forward list") [`<iterator>`](../header/iterator "cpp/header/iterator") [`<list>`](../header/list "cpp/header/list") [`<map>`](../header/map "cpp/header/map") [`<regex>`](../header/regex "cpp/header/regex") [`<set>`](../header/set "cpp/header/set") [`<string>`](../header/string "cpp/header/string") [`<unordered_map>`](../header/unordered_map "cpp/header/unordered map") [`<unordered_set>`](../header/unordered_set "cpp/header/unordered set") [`<vector>`](../header/vector "cpp/header/vector") | | `__cpp_lib_not_fn` | 201603L | [`<functional>`](../header/functional "cpp/header/functional") | | `__cpp_lib_null_iterators` | 201304L | [`<iterator>`](../header/iterator "cpp/header/iterator") | | `__cpp_lib_optional` | 202110L | [`<optional>`](../header/optional "cpp/header/optional") | | `__cpp_lib_out_ptr` | 202106L | [`<memory>`](../header/memory "cpp/header/memory") | | `__cpp_lib_parallel_algorithm` | 201603L | [`<algorithm>`](../header/algorithm "cpp/header/algorithm") [`<numeric>`](../header/numeric "cpp/header/numeric") | | `__cpp_lib_polymorphic_allocator` | 201902L | [`<memory_resource>`](../header/memory_resource "cpp/header/memory resource") | | `__cpp_lib_print` | 202207L | [`<print>`](../header/print "cpp/header/print") [`<ostream>`](../header/ostream "cpp/header/ostream") | | `__cpp_lib_quoted_string_io` | 201304L | [`<iomanip>`](../header/iomanip "cpp/header/iomanip") | | `__cpp_lib_ranges` | 202207L | [`<algorithm>`](../header/algorithm "cpp/header/algorithm") [`<functional>`](../header/functional "cpp/header/functional") [`<iterator>`](../header/iterator "cpp/header/iterator") [`<memory>`](../header/memory "cpp/header/memory") [`<ranges>`](../header/ranges "cpp/header/ranges") | | `__cpp_lib_ranges_as_const` | 202207L | [`<ranges>`](../header/ranges "cpp/header/ranges") | | `__cpp_lib_ranges_as_rvalue` | 202207L | [`<ranges>`](../header/ranges "cpp/header/ranges") | | `__cpp_lib_ranges_cartesian_product` | 202207L | [`<ranges>`](../header/ranges "cpp/header/ranges") | | `__cpp_lib_ranges_chunk` | 202202L | [`<ranges>`](../header/ranges "cpp/header/ranges") | | `__cpp_lib_ranges_chunk_by` | 202202L | [`<ranges>`](../header/ranges "cpp/header/ranges") | | `__cpp_lib_ranges_contains` | 202207L | [`<algorithm>`](../header/algorithm "cpp/header/algorithm") | | `__cpp_lib_ranges_fold` | 202207L | [`<algorithm>`](../header/algorithm "cpp/header/algorithm") | | `__cpp_lib_ranges_iota` | 202202L | [`<numeric>`](../header/numeric "cpp/header/numeric") | | `__cpp_lib_ranges_join_with` | 202202L | [`<ranges>`](../header/ranges "cpp/header/ranges") | | `__cpp_lib_ranges_repeat` | 202207L | [`<ranges>`](../header/ranges "cpp/header/ranges") | | `__cpp_lib_ranges_slide` | 202202L | [`<ranges>`](../header/ranges "cpp/header/ranges") | | `__cpp_lib_ranges_starts_ends_with` | 202106L | [`<algorithm>`](../header/algorithm "cpp/header/algorithm") | | `__cpp_lib_ranges_stride` | 202207L | [`<ranges>`](../header/ranges "cpp/header/ranges") | | `__cpp_lib_ranges_to_container` | 202202L | [`<ranges>`](../header/ranges "cpp/header/ranges") | | `__cpp_lib_ranges_zip` | 202110L | [`<ranges>`](../header/ranges "cpp/header/ranges") [`<tuple>`](../header/tuple "cpp/header/tuple") [`<utility>`](../header/utility "cpp/header/utility") | | `__cpp_lib_raw_memory_algorithms` | 201606L | [`<memory>`](../header/memory "cpp/header/memory") | | `__cpp_lib_reference_from_temporary` | 202202L | [`<type_traits>`](../header/type_traits "cpp/header/type traits") | | `__cpp_lib_remove_cvref` | 201711L | [`<type_traits>`](../header/type_traits "cpp/header/type traits") | | `__cpp_lib_result_of_sfinae` | 201210L | [`<functional>`](../header/functional "cpp/header/functional") [`<type_traits>`](../header/type_traits "cpp/header/type traits") | | `__cpp_lib_robust_nonmodifying_seq_ops` | 201304L | [`<algorithm>`](../header/algorithm "cpp/header/algorithm") | | `__cpp_lib_sample` | 201603L | [`<algorithm>`](../header/algorithm "cpp/header/algorithm") | | `__cpp_lib_scoped_lock` | 201703L | [`<mutex>`](../header/mutex "cpp/header/mutex") | | `__cpp_lib_semaphore` | 201907L | [`<semaphore>`](../header/semaphore "cpp/header/semaphore") | | `__cpp_lib_shared_mutex` | 201505L | [`<shared_mutex>`](../header/shared_mutex "cpp/header/shared mutex") | | `__cpp_lib_shared_ptr_arrays` | 201707L | [`<memory>`](../header/memory "cpp/header/memory") | | `__cpp_lib_shared_ptr_weak_type` | 201606L | [`<memory>`](../header/memory "cpp/header/memory") | | `__cpp_lib_shared_timed_mutex` | 201402L | [`<shared_mutex>`](../header/shared_mutex "cpp/header/shared mutex") | | `__cpp_lib_shift` | 202202L | [`<algorithm>`](../header/algorithm "cpp/header/algorithm") | | `__cpp_lib_smart_ptr_for_overwrite` | 202002L | [`<memory>`](../header/memory "cpp/header/memory") | | `__cpp_lib_source_location` | 201907L | [`<source_location>`](../header/source_location "cpp/header/source location") | | `__cpp_lib_span` | 202002L | [`<span>`](../header/span "cpp/header/span") | | `__cpp_lib_spanstream` | 202106L | [`<spanstream>`](../header/spanstream "cpp/header/spanstream") | | `__cpp_lib_ssize` | 201902L | [`<iterator>`](../header/iterator "cpp/header/iterator") | | `__cpp_lib_stacktrace` | 202011L | [`<stacktrace>`](../header/stacktrace "cpp/header/stacktrace") | | `__cpp_lib_start_lifetime_as` | 202207L | [`<memory>`](../header/memory "cpp/header/memory") | | `__cpp_lib_starts_ends_with` | 201711L | [`<string>`](../header/string "cpp/header/string") [`<string_view>`](../header/string_view "cpp/header/string view") | | `__cpp_lib_stdatomic_h` | 202011L | [`<stdatomic.h>`](../header/stdatomic.h "cpp/header/stdatomic.h") | | `__cpp_lib_string_contains` | 202011L | [`<string>`](../header/string "cpp/header/string") [`<string_view>`](../header/string_view "cpp/header/string view") | | `__cpp_lib_string_resize_and_overwrite` | 202110L | [`<string>`](../header/string "cpp/header/string") | | `__cpp_lib_string_udls` | 201304L | [`<string>`](../header/string "cpp/header/string") | | `__cpp_lib_string_view` | 201803L | [`<string>`](../header/string "cpp/header/string") [`<string_view>`](../header/string_view "cpp/header/string view") | | `__cpp_lib_syncbuf` | 201803L | [`<syncstream>`](../header/syncstream "cpp/header/syncstream") | | `__cpp_lib_three_way_comparison` | 201907L | [`<compare>`](../header/compare "cpp/header/compare") | | `__cpp_lib_to_address` | 201711L | [`<memory>`](../header/memory "cpp/header/memory") | | `__cpp_lib_to_array` | 201907L | [`<array>`](../header/array "cpp/header/array") | | `__cpp_lib_to_chars` | 201611L | [`<charconv>`](../header/charconv "cpp/header/charconv") | | `__cpp_lib_to_underlying` | 202102L | [`<utility>`](../header/utility "cpp/header/utility") | | `__cpp_lib_transformation_trait_aliases` | 201304L | [`<type_traits>`](../header/type_traits "cpp/header/type traits") | | `__cpp_lib_transparent_operators` | 201510L | [`<memory>`](../header/memory "cpp/header/memory") [`<functional>`](../header/functional "cpp/header/functional") | | `__cpp_lib_tuple_like` | 202207L | [`<utility>`](../header/utility "cpp/header/utility") [`<tuple>`](../header/tuple "cpp/header/tuple") [`<map>`](../header/map "cpp/header/map") [`<unordered_map>`](../header/unordered_map "cpp/header/unordered map") | | `__cpp_lib_tuple_element_t` | 201402L | [`<tuple>`](../header/tuple "cpp/header/tuple") | | `__cpp_lib_tuples_by_type` | 201304L | [`<utility>`](../header/utility "cpp/header/utility") [`<tuple>`](../header/tuple "cpp/header/tuple") | | `__cpp_lib_type_identity` | 201806L | [`<type_traits>`](../header/type_traits "cpp/header/type traits") | | `__cpp_lib_type_trait_variable_templates` | 201510L | [`<type_traits>`](../header/type_traits "cpp/header/type traits") | | `__cpp_lib_uncaught_exceptions` | 201411L | [`<exception>`](../header/exception "cpp/header/exception") | | `__cpp_lib_unordered_map_try_emplace` | 201411L | [`<unordered_map>`](../header/unordered_map "cpp/header/unordered map") | | `__cpp_lib_unreachable` | 202202L | [`<utility>`](../header/utility "cpp/header/utility") | | `__cpp_lib_unwrap_ref` | 201811L | [`<type_traits>`](../header/type_traits "cpp/header/type traits") | | `__cpp_lib_variant` | 202106L | [`<variant>`](../header/variant "cpp/header/variant") | | `__cpp_lib_void_t` | 201411L | [`<type_traits>`](../header/type_traits "cpp/header/type traits") | Total number of entries: 177. ### Notes Each value in "Value" column follows the pattern: `"yyyymmL"`, where `"yyyy"` is a year, and `"mm"` is a month when the corresponding feature-set was accepted for standardization. Some values where increased since the time of their introduction, if capabilities of given feature where extended. The table above contains only the most recent values (that is, taken from the latest C++ language draft standard). A full set of values, including the initial and intermediate ones, can be found in [this table](../feature_test#Library_features "cpp/feature test"). ### See also | | | | --- | --- | | [**Feature testing**](../feature_test "cpp/feature test") (C++20) | A set of preprocessor macros to test the corresponding to C++ language and library features |
programming_docs
cpp std::optional std::optional ============= | Defined in header `[<optional>](../header/optional "cpp/header/optional")` | | | | --- | --- | --- | | ``` template< class T > class optional; ``` | | (since C++17) | The class template `std::optional` manages an *optional* contained value, i.e. a value that may or may not be present. A common use case for `optional` is the return value of a function that may fail. As opposed to other approaches, such as `[std::pair](http://en.cppreference.com/w/cpp/utility/pair)<T,bool>`, `optional` handles expensive-to-construct objects well and is more readable, as the intent is expressed explicitly. Any instance of `optional<T>` at any given point in time either *contains a value* or *does not contain a value*. If an `optional<T>` *contains a value*, the value is guaranteed to be allocated as part of the `optional` object footprint, i.e. no dynamic memory allocation ever takes place. Thus, an `optional` object models an object, not a pointer, even though `[operator\*()](optional/operator* "cpp/utility/optional/operator*")` and `[operator->()](optional/operator* "cpp/utility/optional/operator*")` are defined. When an object of type `optional<T>` is [contextually converted to `bool`](../language/implicit_cast "cpp/language/implicit cast"), the conversion returns `true` if the object *contains a value* and `false` if it *does not contain a value*. The `optional` object *contains a value* in the following conditions: * The object is initialized with/assigned from a value of type `T` or another `optional` that *contains a value*. The object *does not contain a value* in the following conditions: * The object is default-initialized. * The object is initialized with/assigned from a value of type `[std::nullopt\_t](optional/nullopt_t "cpp/utility/optional/nullopt t")` or an `optional` object that *does not contain a value*. * The member function `[reset()](optional/reset "cpp/utility/optional/reset")` is called. 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](functional/reference_wrapper "cpp/utility/functional/reference wrapper")` of type `T` may be used to hold a reference. In addition, a program is ill-formed if it instantiates an `optional` with the (possibly cv-qualified) tag types `[std::nullopt\_t](optional/nullopt_t "cpp/utility/optional/nullopt t")` or `[std::in\_place\_t](in_place "cpp/utility/in place")`. ### Template parameters | | | | | --- | --- | --- | | T | - | the type of the value to manage initialization state for. The type must meet the requirements of [Destructible](../named_req/destructible "cpp/named req/Destructible") (in particular, array and reference types are not allowed). | ### Member types | Member type | Definition | | --- | --- | | `value_type` | `T` | ### Member functions | | | | --- | --- | | [(constructor)](optional/optional "cpp/utility/optional/optional") | constructs the optional object (public member function) | | [(destructor)](optional/~optional "cpp/utility/optional/~optional") | destroys the contained value, if there is one (public member function) | | [operator=](optional/operator= "cpp/utility/optional/operator=") | assigns contents (public member function) | | Observers | | [operator->operator\*](optional/operator* "cpp/utility/optional/operator*") | accesses the contained value (public member function) | | [operator boolhas\_value](optional/operator_bool "cpp/utility/optional/operator bool") | checks whether the object contains a value (public member function) | | [value](optional/value "cpp/utility/optional/value") | returns the contained value (public member function) | | [value\_or](optional/value_or "cpp/utility/optional/value or") | returns the contained value if available, another value otherwise (public member function) | | Monadic operations | | [and\_then](optional/and_then "cpp/utility/optional/and then") (C++23) | returns the result of the given function on the contained value if it exists, or an empty `optional` otherwise (public member function) | | [transform](optional/transform "cpp/utility/optional/transform") (C++23) | returns an `optional` containing the transformed contained value if it exists, or an empty `optional` otherwise (public member function) | | [or\_else](optional/or_else "cpp/utility/optional/or else") (C++23) | returns the `optional` itself if it contains a value, or the result of the given function otherwise (public member function) | | Modifiers | | [swap](optional/swap "cpp/utility/optional/swap") | exchanges the contents (public member function) | | [reset](optional/reset "cpp/utility/optional/reset") | destroys any contained value (public member function) | | [emplace](optional/emplace "cpp/utility/optional/emplace") | constructs the contained value in-place (public member function) | ### Non-member functions | | | | --- | --- | | [operator==operator!=operator<operator<=operator>operator>=operator<=>](optional/operator_cmp "cpp/utility/optional/operator cmp") (C++17)(C++17)(C++17)(C++17)(C++17)(C++17)(C++20) | compares `optional` objects (function template) | | [make\_optional](optional/make_optional "cpp/utility/optional/make optional") (C++17) | creates an `optional` object (function template) | | [std::swap(std::optional)](optional/swap2 "cpp/utility/optional/swap2") (C++17) | specializes the `[std::swap](../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | ### Helper classes | | | | --- | --- | | [std::hash<std::optional>](optional/hash "cpp/utility/optional/hash") (C++17) | specializes the `[std::hash](hash "cpp/utility/hash")` algorithm (class template specialization) | | [nullopt\_t](optional/nullopt_t "cpp/utility/optional/nullopt t") (C++17) | indicator of optional type with uninitialized state (class) | | [bad\_optional\_access](optional/bad_optional_access "cpp/utility/optional/bad optional access") (C++17) | exception indicating checked access to an optional that doesn't contain a value (class) | ### Helpers | | | | --- | --- | | [nullopt](optional/nullopt "cpp/utility/optional/nullopt") (C++17) | an object of type `nullopt_t` (constant) | | [in\_place in\_place\_type in\_place\_index in\_place\_t in\_place\_type\_t in\_place\_index\_t](in_place "cpp/utility/in place") (C++17) | in-place construction tag (class template) | ### [Deduction guides](optional/deduction_guides "cpp/utility/optional/deduction guides") ### Notes | [Feature-test](feature_test "cpp/utility/feature test") macro | Value | Std | Comment | | --- | --- | --- | --- | | [`__cpp_lib_optional`](../feature_test#Library_features "cpp/feature test") | `201606L` | (C++17) | | [`__cpp_lib_optional`](../feature_test#Library_features "cpp/feature test") | `202106L` | (C++20) | Fully constexpr | | [`__cpp_lib_optional`](../feature_test#Library_features "cpp/feature test") | `202110L` | (C++23) | Monadic operations | ### Example ``` #include <string> #include <functional> #include <iostream> #include <optional> // optional can be used as the return type of a factory that may fail std::optional<std::string> create(bool b) { if (b) return "Godzilla"; return {}; } // std::nullopt can be used to create any (empty) std::optional auto create2(bool b) { return b ? std::optional<std::string>{"Godzilla"} : std::nullopt; } // std::reference_wrapper may be used to return a reference auto create_ref(bool b) { static std::string value = "Godzilla"; return b ? std::optional<std::reference_wrapper<std::string>>{value} : std::nullopt; } int main() { std::cout << "create(false) returned " << create(false).value_or("empty") << '\n'; // optional-returning factory functions are usable as conditions of while and if if (auto str = create2(true)) { std::cout << "create2(true) returned " << *str << '\n'; } if (auto str = create_ref(true)) { // using get() to access the reference_wrapper's value std::cout << "create_ref(true) returned " << str->get() << '\n'; str->get() = "Mothra"; std::cout << "modifying it changed it to " << str->get() << '\n'; } } ``` Output: ``` create(false) returned empty create2(true) returned Godzilla create_ref(true) returned Godzilla modifying it changed it to Mothra ``` ### See also | | | | --- | --- | | [variant](variant "cpp/utility/variant") (C++17) | a type-safe discriminated union (class template) | | [any](any "cpp/utility/any") (C++17) | Objects that hold instances of any [CopyConstructible](../named_req/copyconstructible "cpp/named req/CopyConstructible") type. (class) | cpp std::pair std::pair ========= | Defined in header `[<utility>](../header/utility "cpp/header/utility")` | | | | --- | --- | --- | | ``` template< class T1, class T2 > struct pair; ``` | | | `std::pair` is a class template that provides a way to store two heterogeneous objects as a single unit. A pair is a specific case of a `[std::tuple](tuple "cpp/utility/tuple")` with two elements. If neither `T1` nor `T2` is a possibly cv-qualified class type with non-trivial destructor, or array thereof, the destructor of `pair` is trivial. ### Template parameters | | | | | --- | --- | --- | | T1, T2 | - | the types of the elements that the pair stores. | ### Member types | Member type | Definition | | --- | --- | | `first_type` | `T1` | | `second_type` | `T2` | ### Member objects | Member name | Type | | --- | --- | | `first` | `T1` | | `second` | `T2` | ### Member functions | | | | --- | --- | | [(constructor)](pair/pair "cpp/utility/pair/pair") | constructs new pair (public member function) | | [operator=](pair/operator= "cpp/utility/pair/operator=") | assigns the contents (public member function) | | [swap](pair/swap "cpp/utility/pair/swap") (C++11) | swaps the contents (public member function) | ### Non-member functions | | | | --- | --- | | [make\_pair](pair/make_pair "cpp/utility/pair/make pair") | creates a `pair` object of type, defined by the argument types (function template) | | [operator==operator!=operator<operator<=operator>operator>=operator<=>](pair/operator_cmp "cpp/utility/pair/operator cmp") (removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(C++20) | lexicographically compares the values in the pair (function template) | | [std::swap(std::pair)](pair/swap2 "cpp/utility/pair/swap2") (C++11) | specializes the `[std::swap](../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | | [std::get(std::pair)](pair/get "cpp/utility/pair/get") (C++11) | accesses an element of a `pair` (function template) | ### Helper classes | | | | --- | --- | | [std::tuple\_size<std::pair>](pair/tuple_size "cpp/utility/pair/tuple size") (C++11) | obtains the size of a `pair` (class template specialization) | | [std::tuple\_element<std::pair>](pair/tuple_element "cpp/utility/pair/tuple element") (C++11) | obtains the type of the elements of `pair` (class template specialization) | | [std::basic\_common\_reference<std::pair>](pair/basic_common_reference "cpp/utility/pair/basic common reference") (C++23) | determines the common reference type of two `pair`s (class template specialization) | | [std::common\_type<std::pair>](pair/common_type "cpp/utility/pair/common type") (C++23) | determines the common type of two `pair`s (class template specialization) | ### [Deduction guides](pair/deduction_guides "cpp/utility/pair/deduction guides")(since C++17) ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 2796](https://cplusplus.github.io/LWG/issue2796) | C++98 | triviality of the destructor of `pair` was unspecified | specified | ### See also | | | | --- | --- | | [tuple](tuple "cpp/utility/tuple") (C++11) | implements fixed size container, which holds elements of possibly different types (class template) | | [tie](tuple/tie "cpp/utility/tuple/tie") (C++11) | creates a `[tuple](tuple "cpp/utility/tuple")` of lvalue references or unpacks a tuple into individual objects (function template) | cpp std::source_location std::source\_location ===================== | Defined in header `[<source\_location>](../header/source_location "cpp/header/source location")` | | | | --- | --- | --- | | ``` struct source_location; ``` | | (since C++20) | The `source_location` class represents certain information about the source code, such as file names, line numbers, and function names. Previously, functions that desire to obtain this information about the call site (for logging, testing, or debugging purposes) must use macros so that predefined macros like `__LINE__` and `__FILE__` are expanded in the context of the caller. The `source_location` class provides a better alternative. `source_location` meets the [DefaultConstructible](../named_req/defaultconstructible "cpp/named req/DefaultConstructible"), [CopyConstructible](../named_req/copyconstructible "cpp/named req/CopyConstructible"), [CopyAssignable](../named_req/copyassignable "cpp/named req/CopyAssignable") and [Destructible](../named_req/destructible "cpp/named req/Destructible") requirements. Lvalue of `source_location` meets the [Swappable](../named_req/swappable "cpp/named req/Swappable") requirement. Additionally, the following conditions are `true`: * `[std::is\_nothrow\_move\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_move_constructible)<std::source\_location>`, * `[std::is\_nothrow\_move\_assignable\_v](http://en.cppreference.com/w/cpp/types/is_move_assignable)<std::source\_location>`, and * `[std::is\_nothrow\_swappable\_v](http://en.cppreference.com/w/cpp/types/is_swappable)<std::source\_location>`. It is intended that `source_location` has a small size and can be copied efficiently. It is unspecified whether the copy/move constructors and the copy/move assignment operators of `source_location` are trivial and/or constexpr. ### Member functions | | | --- | | Creation | | [(constructor)](source_location/source_location "cpp/utility/source location/source location") | constructs a new `source_location` with implementation-defined values (public member function) | | [current](source_location/current "cpp/utility/source location/current") [static] | constructs a new `source_location` corresponding to the location of the call site (public static member function) | | Field access | | [line](source_location/line "cpp/utility/source location/line") | return the line number represented by this object (public member function) | | [column](source_location/column "cpp/utility/source location/column") | return the column number represented by this object (public member function) | | [file\_name](source_location/file_name "cpp/utility/source location/file name") | return the file name represented by this object (public member function) | | [function\_name](source_location/function_name "cpp/utility/source location/function name") | return the name of the function represented by this object, if any (public member function) | ### Notes | [Feature-test](feature_test "cpp/utility/feature test") macro | | --- | | [`__cpp_lib_source_location`](../feature_test#Library_features "cpp/feature test") | ### Example ``` #include <iostream> #include <string_view> #include <source_location> void log(const std::string_view message, const std::source_location location = std::source_location::current()) { std::cout << "file: " << location.file_name() << "(" << location.line() << ":" << location.column() << ") `" << location.function_name() << "`: " << message << '\n'; } template <typename T> void fun(T x) { log(x); } int main(int, char*[]) { log("Hello world!"); fun("Hello C++20!"); } ``` Possible output: ``` file: main.cpp(23:8) `int main(int, char**)`: Hello world! file: main.cpp(18:8) `void fun(T) [with T = const char*]`: Hello C++20! ``` ### See also | | | | --- | --- | | [stacktrace\_entry](stacktrace_entry "cpp/utility/stacktrace entry") (C++23) | representation of an evaluation in a stacktrace (class) | | [Filename and line information](../preprocessor/line "cpp/preprocessor/line") | cpp std::tuple std::tuple ========== | Defined in header `[<tuple>](../header/tuple "cpp/header/tuple")` | | | | --- | --- | --- | | ``` template< class... Types > class tuple; ``` | | (since C++11) | Class template `std::tuple` is a fixed-size collection of heterogeneous values. It is a generalization of `[std::pair](pair "cpp/utility/pair")`. If `[std::is\_trivially\_destructible](http://en.cppreference.com/w/cpp/types/is_destructible)<Ti>::value` is `true` for every `Ti` in `Types`, the destructor of `tuple` is trivial. ### Template parameters | | | | | --- | --- | --- | | Types... | - | the types of the elements that the tuple stores. Empty list is supported. | ### Member functions | | | | --- | --- | | [(constructor)](tuple/tuple "cpp/utility/tuple/tuple") (C++11) | constructs a new `tuple` (public member function) | | [operator=](tuple/operator= "cpp/utility/tuple/operator=") (C++11) | assigns the contents of one `tuple` to another (public member function) | | [swap](tuple/swap "cpp/utility/tuple/swap") (C++11) | swaps the contents of two `tuple`s (public member function) | ### Non-member functions | | | | --- | --- | | [make\_tuple](tuple/make_tuple "cpp/utility/tuple/make tuple") (C++11) | creates a `tuple` object of the type defined by the argument types (function template) | | [tie](tuple/tie "cpp/utility/tuple/tie") (C++11) | creates a `tuple` of lvalue references or unpacks a tuple into individual objects (function template) | | [forward\_as\_tuple](tuple/forward_as_tuple "cpp/utility/tuple/forward as tuple") (C++11) | creates a `tuple` of [forwarding references](../language/reference#Forwarding_references "cpp/language/reference") (function template) | | [tuple\_cat](tuple/tuple_cat "cpp/utility/tuple/tuple cat") (C++11) | creates a `tuple` by concatenating any number of tuples (function template) | | [std::get(std::tuple)](tuple/get "cpp/utility/tuple/get") (C++11) | tuple accesses specified element (function template) | | [operator==operator!=operator<operator<=operator>operator>=operator<=>](tuple/operator_cmp "cpp/utility/tuple/operator cmp") (removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(C++20) | lexicographically compares the values in the tuple (function template) | | [std::swap(std::tuple)](tuple/swap2 "cpp/utility/tuple/swap2") (C++11) | specializes the `[std::swap](../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | ### Helper classes | | | | --- | --- | | [std::tuple\_size<std::tuple>](tuple/tuple_size "cpp/utility/tuple/tuple size") (C++11) | obtains the size of `tuple` at compile time (class template specialization) | | [std::tuple\_element<std::tuple>](tuple/tuple_element "cpp/utility/tuple/tuple element") (C++11) | obtains the type of the specified element (class template specialization) | | [std::uses\_allocator<std::tuple>](tuple/uses_allocator "cpp/utility/tuple/uses allocator") (C++11) | specializes the `[std::uses\_allocator](../memory/uses_allocator "cpp/memory/uses allocator")` type trait (class template specialization) | | [std::basic\_common\_reference<*tuple-like*>](tuple/basic_common_reference "cpp/utility/tuple/basic common reference") (C++23) | determines the common reference type of a `tuple` and a tuple-like type (class template specialization) | | [std::common\_type<*tuple-like*>](tuple/common_type "cpp/utility/tuple/common type") (C++23) | determines the common type of a `tuple` and a tuple-like type (class template specialization) | | [ignore](tuple/ignore "cpp/utility/tuple/ignore") (C++11) | placeholder to skip an element when unpacking a `tuple` using [`tie`](tuple/tie "cpp/utility/tuple/tie") (constant) | ### [Deduction guides](tuple/deduction_guides "cpp/utility/tuple/deduction guides") (since C++17) ### Notes Until [N4387](https://wg21.link/N4387) (applied as a defect report for C++11), a function could not return a tuple using copy-list-initialization: ``` std::tuple<int, int> foo_tuple() { return {1, -1}; // Error until N4387 return std::tuple<int, int>{1, -1}; // Always works return std::make_tuple(1, -1); // Always works } ``` ### Example ``` #include <tuple> #include <iostream> #include <string> #include <stdexcept> std::tuple<double, char, std::string> get_student(int id) { if (id == 0) return std::make_tuple(3.8, 'A', "Lisa Simpson"); if (id == 1) return std::make_tuple(2.9, 'C', "Milhouse Van Houten"); if (id == 2) return std::make_tuple(1.7, 'D', "Ralph Wiggum"); throw std::invalid_argument("id"); } int main() { auto student0 = get_student(0); std::cout << "ID: 0, " << "GPA: " << std::get<0>(student0) << ", " << "grade: " << std::get<1>(student0) << ", " << "name: " << std::get<2>(student0) << '\n'; double gpa1; char grade1; std::string name1; std::tie(gpa1, grade1, name1) = get_student(1); std::cout << "ID: 1, " << "GPA: " << gpa1 << ", " << "grade: " << grade1 << ", " << "name: " << name1 << '\n'; // C++17 structured binding: auto [ gpa2, grade2, name2 ] = get_student(2); std::cout << "ID: 2, " << "GPA: " << gpa2 << ", " << "grade: " << grade2 << ", " << "name: " << name2 << '\n'; } ``` Output: ``` ID: 0, GPA: 3.8, grade: A, name: Lisa Simpson ID: 1, GPA: 2.9, grade: C, name: Milhouse Van Houten ID: 2, GPA: 1.7, grade: D, name: Ralph Wiggum ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 2796](https://cplusplus.github.io/LWG/issue2796) | C++11 | triviality of the destructor of `tuple` was unspecified | specified | ### References * C++20 standard (ISO/IEC 14882:2020): + 20.5 Tuples [tuple] * C++17 standard (ISO/IEC 14882:2017): + 23.5 Tuples [tuple] * C++14 standard (ISO/IEC 14882:2014): + 20.4 Tuples [tuple] * C++11 standard (ISO/IEC 14882:2011): + 20.4 Tuples [tuple] ### See also | | | | --- | --- | | [pair](pair "cpp/utility/pair") | implements binary tuple, i.e. a pair of values (class template) |
programming_docs
cpp std::basic_stacktrace std::basic\_stacktrace ====================== | Defined in header `[<stacktrace>](../header/stacktrace "cpp/header/stacktrace")` | | | | --- | --- | --- | | ``` template< class Allocator > class basic_stacktrace; ``` | (1) | (since C++23) | | ``` using stacktrace = std::basic_stacktrace<std::allocator<std::stacktrace_entry>>; ``` | (2) | (since C++23) | | ``` namespace pmr { using stacktrace = std::basic_stacktrace<std::pmr::polymorphic_allocator<std::stacktrace_entry>>; } ``` | (3) | (since C++23) | 1) The `basic_stacktrace` class template represents a snapshot of the whole stacktrace or its given part. It satisfies the requirement of [AllocatorAwareContainer](../named_req/allocatorawarecontainer "cpp/named req/AllocatorAwareContainer"), [SequenceContainer](../named_req/sequencecontainer "cpp/named req/SequenceContainer"), and [ReversibleContainer](../named_req/reversiblecontainer "cpp/named req/ReversibleContainer"), except that only move, assignment, swap, and operations for const-qualified sequence containers are supported, and the semantics of comparison functions are different from those required for a container. 2) Convenience type alias for the `basic_stacktrace` using the default `[std::allocator](../memory/allocator "cpp/memory/allocator")`. 3) Convenience type alias for the `basic_stacktrace` using the [polymorphic allocator](../memory/polymorphic_allocator "cpp/memory/polymorphic allocator"). The *invocation sequence* of the current evaluation \(\small{ {x}\_{0} }\)x0 in the current thread of execution is a sequence \(\small{ ({x}\_{0}, \dots, {x}\_{n})}\)(x0, ..., xn) of evaluations such that, for \(\small{i \ge 0}\)i≥0, \(\small{ {x}\_{i} }\)xi is within the function invocation \(\small{ {x}\_{i+1} }\)xi+1. A *stacktrace* is an approximate representation of an invocation sequence and consists of stacktrace entries. A *stacktrace entry* represents an evaluation in a stacktrace. It is represented by `std::stacktrace_entry` in the C++ standard library. ### Template parameters | | | | | --- | --- | --- | | Allocator | - | An allocator that is used to acquire/release memory and to construct/destroy the elements in that memory. The type must meet the requirements of [Allocator](../named_req/allocator "cpp/named req/Allocator"). The program is ill-formed if `Allocator::value_type` is not `std::stacktrace_entry`. | ### Member types | Member type | Definition | | --- | --- | | `value_type`(C++23) | `std::stacktrace_entry` | | `const_reference`(C++23) | `const value_type&` | | `reference`(C++23) | `value_type&` | | `const_iterator`(C++23) | implementation-defined const [LegacyRandomAccessIterator](../named_req/randomaccessiterator "cpp/named req/RandomAccessIterator") type that models [`random_access_iterator`](../iterator/random_access_iterator "cpp/iterator/random access iterator") | | `iterator`(C++23) | `const_iterator` | | `reverse_iterator`(C++23) | `[std::reverse\_iterator](http://en.cppreference.com/w/cpp/iterator/reverse_iterator)<iterator>` | | `reverse_const_iterator`(C++23) | `[std::reverse\_iterator](http://en.cppreference.com/w/cpp/iterator/reverse_iterator)<const_iterator>` | | `difference_type`(C++23) | implementation-defined signed integer type | | `size_type`(C++23) | implementation-defined unsigned integer type | | `allocator_type`(C++23) | `Allocator` | ### Member functions | | | | --- | --- | | [(constructor)](basic_stacktrace/basic_stacktrace "cpp/utility/basic stacktrace/basic stacktrace") (C++23) | creates a new `basic_stacktrace` (public member function) | | [(destructor)](basic_stacktrace/~basic_stacktrace "cpp/utility/basic stacktrace/~basic stacktrace") (C++23) | destroys the `basic_stacktrace` (public member function) | | [operator=](basic_stacktrace/operator= "cpp/utility/basic stacktrace/operator=") (C++23) | assigns to the `basic_stacktrace` (public member function) | | [current](basic_stacktrace/current "cpp/utility/basic stacktrace/current") [static] (C++23) | obtains the current stacktrace or its given part (public static member function) | | [get\_allocator](basic_stacktrace/get_allocator "cpp/utility/basic stacktrace/get allocator") (C++23) | returns the associated allocator (public member function) | | Iterators | | [begincbegin](basic_stacktrace/begin "cpp/utility/basic stacktrace/begin") (C++23) | returns an iterator to the beginning (public member function) | | [endcend](basic_stacktrace/end "cpp/utility/basic stacktrace/end") (C++23) | returns an iterator to the end (public member function) | | [rbegincrbegin](basic_stacktrace/rbegin "cpp/utility/basic stacktrace/rbegin") (C++23) | returns a reverse iterator to the beginning (public member function) | | [rendcrend](basic_stacktrace/rend "cpp/utility/basic stacktrace/rend") (C++23) | returns a reverse iterator to the end (public member function) | | Capacity | | [empty](basic_stacktrace/empty "cpp/utility/basic stacktrace/empty") (C++23) | checks whether the `basic_stacktrace` is empty (public member function) | | [size](basic_stacktrace/size "cpp/utility/basic stacktrace/size") (C++23) | returns the number of stacktrace entries (public member function) | | [max\_size](basic_stacktrace/max_size "cpp/utility/basic stacktrace/max size") (C++23) | returns the maximum possible number of stacktrace entries (public member function) | | Element access | | [operator[]](basic_stacktrace/operator_at "cpp/utility/basic stacktrace/operator at") (C++23) | access specified stacktrace entry (public member function) | | [at](basic_stacktrace/at "cpp/utility/basic stacktrace/at") (C++23) | access specified stacktrace entry with bounds checking (public member function) | | Modifiers | | [swap](basic_stacktrace/swap "cpp/utility/basic stacktrace/swap") (C++23) | swaps the contents (public member function) | ### Non-member functions | | | | --- | --- | | [operator==operator<=>](basic_stacktrace/operator_cmp "cpp/utility/basic stacktrace/operator cmp") (C++23) | compares the sizes and the contents of two `basic_stacktrace` values (function template) | | [std::swap(std::basic\_stacktrace)](basic_stacktrace/swap2 "cpp/utility/basic stacktrace/swap2") (C++23) | specializes the `[std::swap](../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | | [to\_string](basic_stacktrace/to_string "cpp/utility/basic stacktrace/to string") (C++23) | returns a string with a description of the `basic_stacktrace` (function template) | | [operator<<](basic_stacktrace/operator_ltlt "cpp/utility/basic stacktrace/operator ltlt") (C++23) | performs stream output of `basic_stracktrace` (function template) | ### Helper classes | | | | --- | --- | | [std::hash<std::basic\_stacktrace>](basic_stacktrace/hash "cpp/utility/basic stacktrace/hash") (C++23) | hash support for `std::basic_stacktrace` (class template specialization) | ### Notes Support for custom allocators is provided for using `basic_stacktrace` on a hot path or in embedded environments. Users can allocate `stacktrace_entry` objects on the stack or in some other place, where appropriate. The sequence of `std::stacktrace_entry` objects owned by a `std::basic_stacktrace` is immutable, and either is empty or represents a contiguous interval of the whole stacktrace. `boost::stacktrace::basic_stacktrace` (available in [Boost.Stacktrace](https://www.boost.org/doc/libs/release/doc/html/stacktrace.html)) can be used instead when `std::basic_stacktrace` is not available. | [Feature-test](feature_test "cpp/utility/feature test") macro | Value | Std | | --- | --- | --- | | [`__cpp_lib_stacktrace`](../feature_test#Library_features "cpp/feature test") | `202011L` | (C++23) | ### Example ### See also | | | | --- | --- | | [stacktrace\_entry](stacktrace_entry "cpp/utility/stacktrace entry") (C++23) | representation of an evaluation in a stacktrace (class) | cpp std::to_chars, std::to_chars_result std::to\_chars, std::to\_chars\_result ====================================== | Defined in header `[<charconv>](../header/charconv "cpp/header/charconv")` | | | | --- | --- | --- | | | (1) | | | ``` std::to_chars_result to_chars( char* first, char* last, /*see below*/ value, int base = 10 ); ``` | (since C++17) (until C++23) | | ``` constexpr std::to_chars_result to_chars( char* first, char* last, /*see below*/ value, int base = 10 ); ``` | (since C++23) | | ``` std::to_chars_result to_chars( char*, char*, bool, int = 10 ) = delete; ``` | (2) | (since C++17) | | ``` std::to_chars_result to_chars( char* first, char* last, float value ); std::to_chars_result to_chars( char* first, char* last, double value ); std::to_chars_result to_chars( char* first, char* last, long double value ); ``` | (3) | (since C++17) | | ``` std::to_chars_result to_chars( char* first, char* last, float value, std::chars_format fmt ); std::to_chars_result to_chars( char* first, char* last, double value, std::chars_format fmt ); std::to_chars_result to_chars( char* first, char* last, long double value, std::chars_format fmt ); ``` | (4) | (since C++17) | | ``` std::to_chars_result to_chars( char* first, char* last, float value, std::chars_format fmt, int precision ); std::to_chars_result to_chars( char* first, char* last, double value, std::chars_format fmt, int precision ); std::to_chars_result to_chars( char* first, char* last, long double value, std::chars_format fmt, int precision ); ``` | (5) | (since C++17) | | Helper types | | | | ``` struct to_chars_result { char* ptr; std::errc ec; }; ``` | (6) | (since C++17) | Converts `value` into a character string by successively filling the range `[first, last)`, where `[first, last)` is required to be a valid range. 1) Integer formatters: `value` is converted to a string of digits in the given `base` (with no redundant leading zeroes). Digits in the range `10..35` (inclusive) are represented as lowercase characters `a..z`. If value is less than zero, the representation starts with a minus sign. The library provides overloads for all signed and unsigned integer types and for the type `char` as the type of the parameter `value`. 2) Overload for `bool` is deleted. `to_chars` rejects argument of type `bool` because the result would be `"0"`/`"1"` but not `"false"`/`"true"` if it is permitted. 3) value is converted to a string as if by `[std::printf](../io/c/fprintf "cpp/io/c/fprintf")` in the default ("C") locale. The conversion specifier is `f` or `e` (resolving in favor of `f` in case of a tie), chosen according to the requirement for a shortest representation: the string representation consists of the smallest number of characters such that there is at least one digit before the radix point (if present) and parsing the representation using the corresponding [`std::from_chars`](from_chars "cpp/utility/from chars") function recovers value exactly. If there are several such representations, one with the smallest difference to `value` is chosen, resolving any remaining ties using rounding according to `[std::round\_to\_nearest](../types/numeric_limits/float_round_style "cpp/types/numeric limits/float round style")` 4) same as (3), but the conversion specified for the as-if printf is `f` if `fmt` is [`std::chars_format::fixed`](chars_format "cpp/utility/chars format"), `e` if `fmt` is [`std::chars_format::scientific`](chars_format "cpp/utility/chars format"), `a` (but without leading "0x" in the result) if `fmt` is [`std::chars_format::hex`](chars_format "cpp/utility/chars format"), and `g` if `fmt` is [`chars_format::general`](chars_format "cpp/utility/chars format"). 5) same as (4), except the precision is specified by the parameter `precision` rather than by the shortest representation requirement. 6) The return type (see Return value below). `std::to_chars_result` has no base classes, or members other than `ptr`, `ec` and implicitly declared special member functions. ### Parameters | | | | | --- | --- | --- | | first, last | - | character range to write to | | value | - | the value to convert to its string representation | | base | - | integer base to use: a value between 2 and 36 (inclusive). | | fmt | - | floating-point formatting to use, a bitmask of type [`std::chars_format`](chars_format "cpp/utility/chars format") | | precision | - | floating-point precision to use | ### Return value On success, returns a value of type `to_chars_result` such that `ec` equals value-initialized `[std::errc](../error/errc "cpp/error/errc")` and `ptr` is the one-past-the-end pointer of the characters written. Note that the string is *not* NUL-terminated. On error, returns a value of type `to_chars_result` holding `[std::errc::value\_too\_large](../error/errc "cpp/error/errc")` in `ec`, a copy of the value `last` in `ptr`, and leaves the contents of the range `[first, last)` in unspecified state. operator==(std::to\_chars\_result) ----------------------------------- | | | | | --- | --- | --- | | ``` friend bool operator==( const to_chars_result&, const to_chars_result& ) = default; ``` | | (since C++20) | Checks if `ptr` and `ec` of both arguments are equal respectively. This function is not visible to ordinary [unqualified](../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../language/adl "cpp/language/adl") when `std::to_chars_result` is an associated class of the arguments. The `!=` operator is [synthesized](../language/operators#Relational_operators "cpp/language/operators") from `operator==`. ### Exceptions Throws nothing. ### Notes Unlike other formatting functions in C++ and C libraries, `std::to_chars` is locale-independent, non-allocating, and non-throwing. Only a small subset of formatting policies used by other libraries (such as `[std::sprintf](../io/c/fprintf "cpp/io/c/fprintf")`) is provided. This is intended to allow the fastest possible implementation that is useful in common high-throughput contexts such as text-based interchange (JSON or XML). The guarantee that `std::from_chars` can recover every floating-point value formatted by `to_chars` exactly is only provided if both functions are from the same implementation. It is required to explicitly cast a `bool` value to another integer type if it is wanted to format the value as `"0"`/`"1"`. | [Feature-test](feature_test "cpp/utility/feature test") macro | Value | Std | | --- | --- | --- | | [`__cpp_lib_to_chars`](../feature_test#Library_features "cpp/feature test") | `201611L` | (C++17) | | [`__cpp_lib_constexpr_charconv`](../feature_test#Library_features "cpp/feature test") | `202207L` | (C++23) | ### Example ``` #include <array> #include <charconv> #include <iostream> #include <string_view> #include <system_error> void show_to_chars(auto... format_args) { std::array<char, 10> str; if(auto [ptr, ec] = std::to_chars(str.data(), str.data() + str.size(), format_args...); ec == std::errc()) { std::cout << std::string_view (str.data(), ptr) << '\n'; // (str.data(), ptr - str.data()) // C++17 alt, using string_view(ptr, length) } else { std::cout << std::make_error_code(ec).message() << '\n'; } } int main() { show_to_chars(42); show_to_chars(+3.14159F); show_to_chars(-3.14159, std::chars_format::fixed); show_to_chars(-3.14159, std::chars_format::scientific, 3); show_to_chars(3.1415926535, std::chars_format::fixed, 10); } ``` Output: ``` 42 3.14159 -3.14159 -3.142e+00 Value too large for defined data type ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 2955](https://cplusplus.github.io/LWG/issue2955) | C++17 | this function was in [`<utility>`](../header/utility "cpp/header/utility") and used `[std::error\_code](../error/error_code "cpp/error/error code")` | moved to [`<charconv>`](../header/charconv "cpp/header/charconv") and uses `[std::errc](../error/errc "cpp/error/errc")` | | [LWG 3266](https://cplusplus.github.io/LWG/issue3266) | C++17 | `bool` argument was accepted and promoted to `int` | rejected by a deleted overload | | [LWG 3373](https://cplusplus.github.io/LWG/issue3373) | C++17 | `to_chars_result` might have additional members | additional members are disallowed | ### See also | | | | --- | --- | | [from\_chars](from_chars "cpp/utility/from chars") (C++17) | converts a character sequence to an integer or floating-point value (function) | | [to\_string](../string/basic_string/to_string "cpp/string/basic string/to string") (C++11) | converts an integral or floating point value to `string` (function) | | [printffprintfsprintfsnprintf](../io/c/fprintf "cpp/io/c/fprintf") (C++11) | prints formatted output to `[stdout](../io/c/std_streams "cpp/io/c/std streams")`, a file stream or a buffer (function) | | [operator<<](../io/basic_ostream/operator_ltlt "cpp/io/basic ostream/operator ltlt") | inserts formatted data (public member function of `std::basic_ostream<CharT,Traits>`) | cpp std::to_underlying std::to\_underlying =================== | Defined in header `[<utility>](../header/utility "cpp/header/utility")` | | | | --- | --- | --- | | ``` template< class Enum > constexpr std::underlying_type_t<Enum> to_underlying( Enum e ) noexcept; ``` | | (since C++23) | Converts an enumeration to its underlying type. Equivalent to `return static\_cast<[std::underlying\_type\_t](http://en.cppreference.com/w/cpp/types/underlying_type)<Enum>>(e);`. ### Parameters | | | | | --- | --- | --- | | e | - | enumeration value to convert | ### Return value The integer value of the underlying type of `Enum`, converted from `e`. ### Notes `std::to_underlying` can be used to avoid converting an enumeration to an integer type other than its underlying type. | [Feature-test](feature_test "cpp/utility/feature test") macro | | --- | | [`__cpp_lib_to_underlying`](../feature_test#Library_features "cpp/feature test") | ### Example ``` #include <cstdint> #include <iomanip> #include <iostream> #include <type_traits> #include <utility> int main() { enum class E1 : char { e }; static_assert(std::is_same_v<char, decltype(std::to_underlying(E1::e))>); enum struct E2 : long { e }; static_assert(std::is_same_v<long, decltype(std::to_underlying(E2::e))>); enum E3 : unsigned { e }; static_assert(std::is_same_v<unsigned, decltype(std::to_underlying(e))>); enum class ColorMask : std::uint32_t { red = 0xFF, green = (red << 8), blue = (green << 8), alpha = (blue << 8) }; std::cout << std::hex << std::uppercase << std::setfill('0') << std::setw(8) << std::to_underlying(ColorMask::red) << '\n' << std::setw(8) << std::to_underlying(ColorMask::green) << '\n' << std::setw(8) << std::to_underlying(ColorMask::blue) << '\n' << std::setw(8) << std::to_underlying(ColorMask::alpha) << '\n'; // std::underlying_type_t<ColorMask> x = ColorMask::alpha; // Error: no known conversion [[maybe_unused]] std::underlying_type_t<ColorMask> y = std::to_underlying(ColorMask::alpha); // OK } ``` Output: ``` 000000FF 0000FF00 00FF0000 FF000000 ``` ### See also | | | | --- | --- | | [underlying\_type](../types/underlying_type "cpp/types/underlying type") (C++11) | obtains the underlying integer type for a given enumeration type (class template) | | [is\_enum](../types/is_enum "cpp/types/is enum") (C++11) | checks if a type is an enumeration type (class template) | | [is\_scoped\_enum](../types/is_scoped_enum "cpp/types/is scoped enum") (C++23) | checks if a type is a scoped enumeration type (class template) |
programming_docs
cpp std::apply std::apply ========== | Defined in header `[<tuple>](../header/tuple "cpp/header/tuple")` | | | | --- | --- | --- | | ``` template< class F, class Tuple > constexpr decltype(auto) apply( F&& f, Tuple&& t ); ``` | | (since C++17) (until C++23) | | ``` template< class F, class Tuple > constexpr decltype(auto) apply( F&& f, Tuple&& t ) noexcept(/* see below */); ``` | | (since C++23) | Invoke the [Callable](../named_req/callable "cpp/named req/Callable") object `f` with a tuple of arguments. ### Parameters | | | | | --- | --- | --- | | f | - | [Callable](../named_req/callable "cpp/named req/Callable") object to be invoked | | t | - | tuple whose elements to be used as arguments to `f` | ### Return value The value returned by `f`. ### Exceptions | | | | --- | --- | | (none). | (until C++23) | | [`noexcept`](../language/noexcept_spec "cpp/language/noexcept spec") specification: `noexcept( noexcept([std::invoke](http://en.cppreference.com/w/cpp/utility/functional/invoke)([std::forward](http://en.cppreference.com/w/cpp/utility/forward)<F>(f), [std::get](http://en.cppreference.com/w/cpp/utility/variant/get)<Is>([std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Tuple>(t))...)). )` where `Is...` denotes the parameter pack:* `0, 1, ..., [std::tuple\_size\_v](http://en.cppreference.com/w/cpp/utility/tuple/tuple_size)<[std::remove\_reference\_t](http://en.cppreference.com/w/cpp/types/remove_reference)<Tuple>> - 1`. | (since C++23) | ### Notes The tuple need not be `[std::tuple](tuple "cpp/utility/tuple")`, and instead may be anything that supports `[std::get](variant/get "cpp/utility/variant/get")` and `std::tuple_size`; in particular, `[std::array](../container/array "cpp/container/array")` and `[std::pair](pair "cpp/utility/pair")` may be used. | [Feature-test](feature_test "cpp/utility/feature test") macro | | --- | | [`__cpp_lib_apply`](../feature_test#Library_features "cpp/feature test") | ### Possible implementation | | | --- | | ``` namespace detail { template <class F, class Tuple, std::size_t... I> constexpr decltype(auto) apply_impl(F&& f, Tuple&& t, std::index_sequence<I...>) { // This implementation is valid since C++20 (via P1065R2) // In C++17, a constexpr counterpart of std::invoke is actually needed here return std::invoke(std::forward<F>(f), std::get<I>(std::forward<Tuple>(t))...); } template <class F, class Tuple, class Idx> inline constexpr bool apply_is_noexcept = false; template <class F, class Tuple, std::size_t... I> inline constexpr bool apply_is_noexcept<F, Tuple, std::index_sequence<I...>> = noexcept(std::invoke(std::declval<F>(), std::get<I>(std::declval<Tuple>())...)); } // namespace detail template <class F, class Tuple> constexpr decltype(auto) apply(F&& f, Tuple&& t) noexcept( // since C++23 detail::apply_is_noexcept<F, Tuple, std::make_index_sequence<std::remove_reference_t<Tuple>>> ) { return detail::apply_impl( std::forward<F>(f), std::forward<Tuple>(t), std::make_index_sequence<std::tuple_size_v<std::remove_reference_t<Tuple>>>{}); } ``` | ### Example ``` #include <iostream> #include <tuple> #include <utility> int add(int first, int second) { return first + second; } template<typename T> T add_generic(T first, T second) { return first + second; } auto add_lambda = [](auto first, auto second) { return first + second; }; template<typename... Ts> std::ostream& operator<<(std::ostream& os, std::tuple<Ts...> const& theTuple) { std::apply ( [&os](Ts const&... tupleArgs) { os << '['; std::size_t n{0}; ((os << tupleArgs << (++n != sizeof...(Ts) ? ", " : "")), ...); os << ']'; }, theTuple ); return os; } int main() { // OK std::cout << std::apply(add, std::pair(1, 2)) << '\n'; // Error: can't deduce the function type // std::cout << std::apply(add_generic, std::make_pair(2.0f, 3.0f)) << '\n'; // OK std::cout << std::apply(add_lambda, std::pair(2.0f, 3.0f)) << '\n'; // advanced example std::tuple myTuple{25, "Hello", 9.31f, 'c'}; std::cout << myTuple << '\n'; } ``` Output: ``` 3 5 [25, Hello, 9.31, c] ``` ### See also | | | | --- | --- | | [make\_tuple](tuple/make_tuple "cpp/utility/tuple/make tuple") (C++11) | creates a `tuple` object of the type defined by the argument types (function template) | | [forward\_as\_tuple](tuple/forward_as_tuple "cpp/utility/tuple/forward as tuple") (C++11) | creates a `tuple` of [forwarding references](../language/reference#Forwarding_references "cpp/language/reference") (function template) | | [make\_from\_tuple](make_from_tuple "cpp/utility/make from tuple") (C++17) | Construct an object with a tuple of arguments (function template) | | [invokeinvoke\_r](functional/invoke "cpp/utility/functional/invoke") (C++17)(C++23) | invokes any [Callable](../named_req/callable "cpp/named req/Callable") object with given arguments and possibility to specify return type (since C++23) (function template) | cpp std::hash std::hash ========= | Defined in header `[<functional>](../header/functional "cpp/header/functional")` | | | | --- | --- | --- | | ``` template< class Key > struct hash; ``` | | (since C++11) | Each specialization of this template is either *enabled* ("untainted") or *disabled* ("poisoned"). The *enabled* specializations of the `hash` template defines a function object that implements a [hash function](https://en.wikipedia.org/wiki/Hash_function "enwiki:Hash function"). Instances of this function object satisfy [Hash](../named_req/hash "cpp/named req/Hash"). In particular, they define an `operator() const` that: 1. Accepts a single parameter of type `Key`. 2. Returns a value of type `[std::size\_t](http://en.cppreference.com/w/cpp/types/size_t)` that represents the hash value of the parameter. 3. Does not throw exceptions when called. 4. For two parameters `k1` and `k2` that are equal, `std::hash<Key>()(k1) == std::hash<Key>()(k2)`. 5. For two different parameters `k1` and `k2` that are not equal, the probability that `std::hash<Key>()(k1) == std::hash<Key>()(k2)` should be very small, approaching `1.0/[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<[std::size\_t](http://en.cppreference.com/w/cpp/types/size_t)>::max()`. All explicit and partial specializations of `hash` provided by the standard library are [DefaultConstructible](../named_req/defaultconstructible "cpp/named req/DefaultConstructible"), [CopyAssignable](../named_req/copyassignable "cpp/named req/CopyAssignable"), [Swappable](../named_req/swappable "cpp/named req/Swappable") and [Destructible](../named_req/destructible "cpp/named req/Destructible"). User-provided specializations of `hash` also must meet those requirements. The unordered associative containers `[std::unordered\_set](../container/unordered_set "cpp/container/unordered set")`, `[std::unordered\_multiset](../container/unordered_multiset "cpp/container/unordered multiset")`, `[std::unordered\_map](../container/unordered_map "cpp/container/unordered map")`, `[std::unordered\_multimap](../container/unordered_multimap "cpp/container/unordered multimap")` use specializations of the template `std::hash` as the default hash function. For every type `Key` for which neither the library nor the user provides an enabled specialization `std::hash<Key>`, that specialization exists and is disabled. Disabled specializations do not satisfy [Hash](../named_req/hash "cpp/named req/Hash"), do not satisfy [FunctionObject](../named_req/functionobject "cpp/named req/FunctionObject"), and following values are all `false`: * `[std::is\_default\_constructible](http://en.cppreference.com/w/cpp/types/is_default_constructible)<std::hash<Key>>::value` * `[std::is\_copy\_constructible](http://en.cppreference.com/w/cpp/types/is_copy_constructible)<std::hash<Key>>::value` * `[std::is\_move\_constructible](http://en.cppreference.com/w/cpp/types/is_move_constructible)<std::hash<Key>>::value` * `[std::is\_copy\_assignable](http://en.cppreference.com/w/cpp/types/is_copy_assignable)<std::hash<Key>>::value` * `[std::is\_move\_assignable](http://en.cppreference.com/w/cpp/types/is_move_assignable)<std::hash<Key>>::value` In other words, they exist, but cannot be used. ### Notes The actual hash functions are implementation-dependent and are not required to fulfill any other quality criteria except those specified above. Notably, some implementations use trivial (identity) hash functions which map an integer to itself. In other words, these hash functions are designed to work with unordered associative containers, but not as cryptographic hashes, for example. Hash functions are only required to produce the same result for the same input within a single execution of a program; this allows salted hashes that prevent collision denial-of-service attacks. There is no specialization for C strings. `std::hash<const char*>` produces a hash of the value of the pointer (the memory address), it does not examine the contents of any character array. | | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | --- | | Member types | Member type | Definition | | --- | --- | | `argument_type`(deprecated in C++17) | `Key` | | `result_type`(deprecated in C++17) | `[std::size\_t](../types/size_t "cpp/types/size t")` | | (until C++20) | ### Member functions | | | | --- | --- | | [(constructor)](hash/hash "cpp/utility/hash/hash") | constructs a hash function object (public member function) | | [operator()](hash/operator() "cpp/utility/hash/operator()") | calculates the hash of the argument (public member function) | ### Standard specializations for basic types | Defined in header `[<functional>](../header/functional "cpp/header/functional")` | | | | --- | --- | --- | | ``` template<> struct hash<bool>; template<> struct hash<char>; template<> struct hash<signed char>; template<> struct hash<unsigned char>; template<> struct hash<char8_t>; // C++20 template<> struct hash<char16_t>; template<> struct hash<char32_t>; template<> struct hash<wchar_t>; template<> struct hash<short>; template<> struct hash<unsigned short>; template<> struct hash<int>; template<> struct hash<unsigned int>; template<> struct hash<long>; template<> struct hash<long long>; template<> struct hash<unsigned long>; template<> struct hash<unsigned long long>; template<> struct hash<float>; template<> struct hash<double>; template<> struct hash<long double>; template<> struct hash<std::nullptr_t>; template< class T > struct hash<T*>; ``` | | | In addition to the above, the standard library provides specializations for all (scoped and unscoped) enumeration types. These may be (but are not required to be) implemented as `std::hash<[std::underlying\_type](http://en.cppreference.com/w/cpp/types/underlying_type)<Enum>::type>`. The standard library provides enabled specializations of `std::hash` for `[std::nullptr\_t](../types/nullptr_t "cpp/types/nullptr t")` and all cv-unqualified arithmetic types (including any extended integer types), all enumeration types, and all pointer types. Each standard library header that declares the template `std::hash` provides all enabled specializations described above. These headers include [`<string>`](../header/string "cpp/header/string"), [`<system_error>`](../header/system_error "cpp/header/system error"), [`<bitset>`](../header/bitset "cpp/header/bitset"), [`<memory>`](../header/memory "cpp/header/memory"), [`<typeindex>`](../header/typeindex "cpp/header/typeindex"), [`<vector>`](../header/vector "cpp/header/vector"), [`<thread>`](../header/thread "cpp/header/thread"), [`<optional>`](../header/optional "cpp/header/optional"), [`<variant>`](../header/variant "cpp/header/variant"), [`<string_view>`](../header/string_view "cpp/header/string view") (since C++17), [`<coroutine>`](../header/coroutine "cpp/header/coroutine") (since C++20), [`<stacktrace>`](../header/stacktrace "cpp/header/stacktrace") (since C++23). | | | | --- | --- | | All member functions of all standard library specializations of this template are `noexcept` except for the member functions of [`std::hash<std::optional>`](optional/hash "cpp/utility/optional/hash"), [`std::hash<std::variant>`](variant/hash "cpp/utility/variant/hash"), and [`std::hash<std::unique_ptr>`](../memory/unique_ptr/hash "cpp/memory/unique ptr/hash"). | (since C++17) | ### Standard specializations for library types | | | | --- | --- | | [std::hash<std::coroutine\_handle>](../coroutine/coroutine_handle/hash "cpp/coroutine/coroutine handle/hash") (C++20) | hash support for `[std::coroutine\_handle](../coroutine/coroutine_handle "cpp/coroutine/coroutine handle")` (class template specialization) | | [std::hash<std::error\_code>](../error/error_code/hash "cpp/error/error code/hash") (C++11) | hash support for `[std::error\_code](../error/error_code "cpp/error/error code")` (class template specialization) | | [std::hash<std::error\_condition>](../error/error_condition/hash "cpp/error/error condition/hash") (C++17) | hash support for `[std::error\_condition](../error/error_condition "cpp/error/error condition")` (class template specialization) | | [std::hash<std::stacktrace\_entry>](stacktrace_entry/hash "cpp/utility/stacktrace entry/hash") (C++23) | hash support for `std::stacktrace_entry` (class template specialization) | | [std::hash<std::basic\_stacktrace>](basic_stacktrace/hash "cpp/utility/basic stacktrace/hash") (C++23) | hash support for `std::basic_stacktrace` (class template specialization) | | [std::hash<std::optional>](optional/hash "cpp/utility/optional/hash") (C++17) | specializes the `std::hash` algorithm (class template specialization) | | [std::hash<std::variant>](variant/hash "cpp/utility/variant/hash") (C++17) | specializes the `std::hash` algorithm (class template specialization) | | [std::hash<std::monostate>](variant/monostate "cpp/utility/variant/monostate") (C++17) | hash support for `[std::monostate](variant/monostate "cpp/utility/variant/monostate")` (class template specialization) | | [std::hash<std::bitset>](bitset/hash "cpp/utility/bitset/hash") (C++11) | hash support for `[std::bitset](bitset "cpp/utility/bitset")` (class template specialization) | | [std::hash<std::unique\_ptr>](../memory/unique_ptr/hash "cpp/memory/unique ptr/hash") (C++11) | hash support for `[std::unique\_ptr](../memory/unique_ptr "cpp/memory/unique ptr")` (class template specialization) | | [std::hash<std::shared\_ptr>](../memory/shared_ptr/hash "cpp/memory/shared ptr/hash") (C++11) | hash support for `[std::shared\_ptr](../memory/shared_ptr "cpp/memory/shared ptr")` (class template specialization) | | [std::hash<std::type\_index>](../types/type_index/hash "cpp/types/type index/hash") (C++11) | hash support for `[std::type\_index](../types/type_index "cpp/types/type index")` (class template specialization) | | [std::hash<std::string>std::hash<std::u8string>std::hash<std::u16string>std::hash<std::u32string>std::hash<std::wstring>std::hash<std::pmr::string>std::hash<std::pmr::u8string>std::hash<std::pmr::u16string>std::hash<std::pmr::u32string>std::hash<std::pmr::wstring>](../string/basic_string/hash "cpp/string/basic string/hash") (C++11)(C++20)(C++11)(C++11)(C++11)(C++17)(C++20)(C++17)(C++17)(C++17) | hash support for strings (class template specialization) | | [std::hash<std::string\_view>std::hash<std::wstring\_view>std::hash<std::u8string\_view>std::hash<std::u16string\_view>std::hash<std::u32string\_view>](../string/basic_string_view/hash "cpp/string/basic string view/hash") (C++17)(C++17)(C++20)(C++17)(C++17) | hash support for string views (class template specialization) | | [std::hash<std::vector<bool>>](../container/vector_bool/hash "cpp/container/vector bool/hash") (C++11) | hash support for `[std::vector](http://en.cppreference.com/w/cpp/container/vector)<bool>` (class template specialization) | | [std::hash<std::filesystem::path>](../filesystem/path/hash "cpp/filesystem/path/hash") (C++17) | hash support for `[std::filesystem::path](../filesystem/path "cpp/filesystem/path")` (class template specialization) | | [std::hash<std::thread::id>](../thread/thread/id/hash "cpp/thread/thread/id/hash") (C++11) | hash support for `[std::thread::id](../thread/thread/id "cpp/thread/thread/id")` (class template specialization) | Note: additional specializations for `std::pair` and the standard container types, as well as utility functions to compose hashes are available in [`boost::hash`](https://www.boost.org/doc/libs/release/libs/container_hash/doc/html/hash.html#ref). ### Example ``` #include <iostream> #include <iomanip> #include <functional> #include <string> #include <unordered_set> struct S { std::string first_name; std::string last_name; }; bool operator==(const S& lhs, const S& rhs) { return lhs.first_name == rhs.first_name && lhs.last_name == rhs.last_name; } // custom hash can be a standalone function object: struct MyHash { std::size_t operator()(S const& s) const noexcept { std::size_t h1 = std::hash<std::string>{}(s.first_name); std::size_t h2 = std::hash<std::string>{}(s.last_name); return h1 ^ (h2 << 1); // or use boost::hash_combine } }; // custom specialization of std::hash can be injected in namespace std template<> struct std::hash<S> { std::size_t operator()(S const& s) const noexcept { std::size_t h1 = std::hash<std::string>{}(s.first_name); std::size_t h2 = std::hash<std::string>{}(s.last_name); return h1 ^ (h2 << 1); // or use boost::hash_combine } }; int main() { std::string str = "Meet the new boss..."; std::size_t str_hash = std::hash<std::string>{}(str); std::cout << "hash(" << std::quoted(str) << ") = " << str_hash << '\n'; S obj = { "Hubert", "Farnsworth" }; // using the standalone function object std::cout << "hash(" << std::quoted(obj.first_name) << ", " << std::quoted(obj.last_name) << ") = " << MyHash{}(obj) << " (using MyHash)\n" << std::setw(31) << "or " << std::hash<S>{}(obj) << " (using injected std::hash<S> specialization)\n"; // custom hash makes it possible to use custom types in unordered containers // The example will use the injected std::hash<S> specialization above, // to use MyHash instead, pass it as a second template argument std::unordered_set<S> names = {obj, {"Bender", "Rodriguez"}, {"Turanga", "Leela"} }; for(auto& s: names) std::cout << std::quoted(s.first_name) << ' ' << std::quoted(s.last_name) << '\n'; } ``` Possible output: ``` hash("Meet the new boss...") = 1861821886482076440 hash("Hubert", "Farnsworth") = 17622465712001802105 (using MyHash) or 17622465712001802105 (using injected std::hash<S> specialization) "Turanga" "Leela" "Bender" "Rodriguez" "Hubert" "Farnsworth" ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 2148](https://cplusplus.github.io/LWG/issue2148) | C++11 | specializations for enumerations were missing | provided | | [LWG 2543](https://cplusplus.github.io/LWG/issue2543) | C++11 | `hash` might not be SFINAE-friendly | made SFINAE-friendly via disabled specializations | | [LWG 2817](https://cplusplus.github.io/LWG/issue2817) | C++11 | specialization for `nullptr_t` was missing | provided | cpp std::from_chars, std::from_chars_result std::from\_chars, std::from\_chars\_result ========================================== | Defined in header `[<charconv>](../header/charconv "cpp/header/charconv")` | | | | --- | --- | --- | | | (1) | | | ``` std::from_chars_result from_chars( const char* first, const char* last, /*see below*/& value, int base = 10 ); ``` | (since C++17) (until C++23) | | ``` constexpr std::from_chars_result from_chars( const char* first, const char* last, /*see below*/& value, int base = 10 ); ``` | (since C++23) | | ``` std::from_chars_result from_chars( const char* first, const char* last, float& value, std::chars_format fmt = std::chars_format::general ); ``` | (2) | (since C++17) | | ``` std::from_chars_result from_chars( const char* first, const char* last, double& value, std::chars_format fmt = std::chars_format::general ); ``` | (3) | (since C++17) | | ``` std::from_chars_result from_chars( const char* first, const char* last, long double& value, std::chars_format fmt = std::chars_format::general ); ``` | (4) | (since C++17) | | Helper types | | | | ``` struct from_chars_result { const char* ptr; std::errc ec; }; ``` | (5) | (since C++17) | Analyzes the character sequence `[first,last)` for a pattern described below. If no characters match the pattern or if the value obtained by parsing the matched characters is not representable in the type of `value`, `value` is unmodified, otherwise the characters matching the pattern are interpreted as a text representation of an arithmetic value, which is stored in `value`. 1) Integer parsers: Expects the pattern identical to the one used by `[std::strtol](../string/byte/strtol "cpp/string/byte/strtol")` in the default ("C") locale and the given non-zero numeric base, except that * `"0x"` or `"0X"` prefixes are not recognized if `base` is 16 * only the minus sign is recognized (not the plus sign), and only for signed integer types of `value` * leading whitespace is not ignored. The library provides overloads for all signed and unsigned integer types and `char` as the referenced type of the parameter `value`. 2-4) Floating-point parsers: Expects the pattern identical to the one used by `[std::strtod](../string/byte/strtof "cpp/string/byte/strtof")` in the default ("C") locale, except that * the plus sign is not recognized outside of the exponent (only the minus sign is permitted at the beginning) * if `fmt` has [`std::chars_format::scientific`](chars_format "cpp/utility/chars format") set but not [`std::chars_format::fixed`](chars_format "cpp/utility/chars format"), the exponent part is required (otherwise it is optional) * if `fmt` has [`std::chars_format::fixed`](chars_format "cpp/utility/chars format") set but not [`std::chars_format::scientific`](chars_format "cpp/utility/chars format"), the optional exponent is not permitted * if `fmt` is [`std::chars_format::hex`](chars_format "cpp/utility/chars format"), the prefix `"0x"` or `"0X"` is not permitted (the string `"0x123"` parses as the value `"0"` with unparsed remainder `"x123"`) * leading whitespace is not ignored. In any case, the resulting value is one of at most two floating-point values closest to the value of the string matching the pattern, after rounding according to `[std::round\_to\_nearest](../types/numeric_limits/float_round_style "cpp/types/numeric limits/float round style")`. 5) The return type (see Return value below). `std::from_chars_result` has no base classes, or members other than `ptr`, `ec` and implicitly declared special member functions. ### Parameters | | | | | --- | --- | --- | | first, last | - | valid character range to parse | | value | - | the out-parameter where the parsed value is stored if successful | | base | - | integer base to use: a value between 2 and 36 (inclusive). | | fmt | - | floating-point formatting to use, a bitmask of type [`std::chars_format`](chars_format "cpp/utility/chars format") | ### Return value On success, returns a value of type `from_chars_result` such that `ptr` points at the first character not matching the pattern, or has the value equal to `last` if all characters match and `ec` is value-initialized. If there is no pattern match, returns a value of type `from_chars_result` such that `ptr` equals `first` and `ec` equals `[std::errc::invalid\_argument](../error/errc "cpp/error/errc")`. `value` is unmodified. If the pattern was matched, but the parsed value is not in the range representable by the type of `value`, returns value of type `from_chars_result` such that `ec` equals `[std::errc::result\_out\_of\_range](../error/errc "cpp/error/errc")` and `ptr` points at the first character not matching the pattern. `value` is unmodified. operator==(std::from\_chars\_result) ------------------------------------- | | | | | --- | --- | --- | | ``` friend bool operator==( const from_chars_result&, const from_chars_result& ) = default; ``` | | (since C++20) | Checks if `ptr` and `ec` of both arguments are equal respectively. This function is not visible to ordinary [unqualified](../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../language/adl "cpp/language/adl") when `std::from_chars_result` is an associated class of the arguments. The `!=` operator is [synthesized](../language/operators#Relational_operators "cpp/language/operators") from `operator==`. ### Exceptions Throws nothing. ### Notes Unlike other parsing functions in C++ and C libraries, `std::from_chars` is locale-independent, non-allocating, and non-throwing. Only a small subset of parsing policies used by other libraries (such as `[std::sscanf](../io/c/fscanf "cpp/io/c/fscanf")`) is provided. This is intended to allow the fastest possible implementation that is useful in common high-throughput contexts such as text-based interchange (JSON or XML). The guarantee that `std::from_chars` can recover every floating-point value formatted by [`std::to_chars`](to_chars "cpp/utility/to chars") exactly is only provided if both functions are from the same implementation. A pattern consisting of a sign with no digits following it is treated as pattern that did not match anything. | [Feature-test](feature_test "cpp/utility/feature test") macro | Value | Std | | --- | --- | --- | | [`__cpp_lib_to_chars`](../feature_test#Library_features "cpp/feature test") | `201611L` | (C++17) | | [`__cpp_lib_constexpr_charconv`](../feature_test#Library_features "cpp/feature test") | `202207L` | (C++23) | ### Example ``` #include <cassert> #include <charconv> #include <iomanip> #include <iostream> #include <optional> #include <string_view> #include <system_error> int main() { for (std::string_view const str : {"1234", "15 foo", "bar", " 42", "5000000000"}) { std::cout << "String: " << std::quoted(str) << ". "; int result{}; auto [ptr, ec] { std::from_chars(str.data(), str.data() + str.size(), result) }; if (ec == std::errc()) { std::cout << "Result: " << result << ", ptr -> " << std::quoted(ptr) << '\n'; } else if (ec == std::errc::invalid_argument) { std::cout << "That isn't a number.\n"; } else if (ec == std::errc::result_out_of_range) { std::cout << "This number is larger than an int.\n"; } } // C++23's constexpr from_char demo: auto to_int = [](std::string_view s) -> std::optional<int> { if (int value; std::from_chars(s.begin(), s.end(), value).ec == std::errc{}) return value; else return std::nullopt; }; assert(to_int("42") == 42); assert(to_int("foo") == std::nullopt); #if __cpp_lib_constexpr_charconv and __cpp_lib_optional >= 202106 static_assert(to_int("42") == 42); static_assert(to_int("foo") == std::nullopt); #endif } ``` Possible output: ``` String: "1234". Result: 1234, ptr -> "" String: "15 foo". Result: 15, ptr -> " foo" String: "bar". That isn't a number. String: " 42". That isn't a number. String: "5000000000". This number is larger than an int. ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 2955](https://cplusplus.github.io/LWG/issue2955) | C++17 | this function was in <utility> and used `[std::error\_code](../error/error_code "cpp/error/error code")` | moved to <charconv> and uses `[std::errc](../error/errc "cpp/error/errc")` | | [LWG 3373](https://cplusplus.github.io/LWG/issue3373) | C++17 | `from_chars_result` might have additional members | additional members are disallowed | ### See also | | | | --- | --- | | [to\_chars](to_chars "cpp/utility/to chars") (C++17) | converts an integer or floating-point value to a character sequence (function) | | [stoistolstoll](../string/basic_string/stol "cpp/string/basic string/stol") (C++11)(C++11)(C++11) | converts a string to a signed integer (function) | | [stofstodstold](../string/basic_string/stof "cpp/string/basic string/stof") (C++11)(C++11)(C++11) | converts a string to a floating point value (function) | | [strtolstrtoll](../string/byte/strtol "cpp/string/byte/strtol") (C++11) | converts a byte string to an integer value (function) | | [strtofstrtodstrtold](../string/byte/strtof "cpp/string/byte/strtof") | converts a byte string to a floating point value (function) | | [scanffscanfsscanf](../io/c/fscanf "cpp/io/c/fscanf") | reads formatted input from `[stdin](../io/c/std_streams "cpp/io/c/std streams")`, a file stream or a buffer (function) | | [operator>>](../io/basic_istream/operator_gtgt "cpp/io/basic istream/operator gtgt") | extracts formatted data (public member function of `std::basic_istream<CharT,Traits>`) |
programming_docs
cpp std::as_const std::as\_const ============== | Defined in header `[<utility>](../header/utility "cpp/header/utility")` | | | | --- | --- | --- | | ``` template< class T > constexpr std::add_const_t<T>& as_const( T& t ) noexcept; ``` | (1) | (since C++17) | | ``` template< class T > void as_const( const T&& ) = delete; ``` | (2) | (since C++17) | 1) Forms lvalue reference to const type of `t`. 2) const rvalue reference overload is deleted to disallow rvalue arguments. ### Possible implementation | | | --- | | ``` template <class T> constexpr std::add_const_t<T>& as_const(T& t) noexcept { return t; } ``` | ### Notes | [Feature-test](feature_test "cpp/utility/feature test") macro | | --- | | [`__cpp_lib_as_const`](../feature_test#Library_features "cpp/feature test") | ### Example ``` #include <string> #include <cassert> #include <utility> #include <type_traits> int main() { std::string mutableString = "Hello World!"; auto&& constRef = std::as_const(mutableString); // mutableString.clear(); // OK // constRef.clear(); // error: 'constRef' is 'const' qualified, // but 'clear' is not marked const assert( &constRef == &mutableString ); assert( &std::as_const( mutableString ) == &mutableString ); using ExprType = std::remove_reference_t<decltype(std::as_const(mutableString))>; static_assert(std::is_same_v<std::remove_const_t<ExprType>, std::string>, "ExprType should be some kind of string." ); static_assert(!std::is_same_v<ExprType, std::string>, "ExprType shouldn't be a mutable string." ); } ``` ### See also | | | | --- | --- | | [is\_const](../types/is_const "cpp/types/is const") (C++11) | checks if a type is const-qualified (class template) | | [add\_cvadd\_constadd\_volatile](../types/add_cv "cpp/types/add cv") (C++11)(C++11)(C++11) | adds `const` or/and `volatile` specifiers to the given type (class template) | | [remove\_cvremove\_constremove\_volatile](../types/remove_cv "cpp/types/remove cv") (C++11)(C++11)(C++11) | removes `const` or/and `volatile` specifiers from the given type (class template) | cpp Function objects Function objects ================ A *function object* is any object for which the function call operator is defined. C++ provides many built-in function objects as well as support for creation and manipulation of new function objects. ### Function wrappers `[std::function](functional/function "cpp/utility/functional/function")` provides support for storing arbitrary function objects. | | | | --- | --- | | [function](functional/function "cpp/utility/functional/function") (C++11) | wraps callable object of any copy constructible type with specified function call signature (class template) | | [move\_only\_function](functional/move_only_function "cpp/utility/functional/move only function") (C++23) | wraps callable object of any type with specified function call signature (class template) | | [bad\_function\_call](functional/bad_function_call "cpp/utility/functional/bad function call") (C++11) | the exception thrown when invoking an empty `[std::function](functional/function "cpp/utility/functional/function")` (class) | | [mem\_fn](functional/mem_fn "cpp/utility/functional/mem fn") (C++11) | creates a function object out of a pointer to a member (function template) | ### Function invocation `[std::invoke](functional/invoke "cpp/utility/functional/invoke")` can invoke any [Callable](../named_req/callable "cpp/named req/Callable") object with given arguments. | | | | --- | --- | | [invokeinvoke\_r](functional/invoke "cpp/utility/functional/invoke") (C++17)(C++23) | invokes any [Callable](../named_req/callable "cpp/named req/Callable") object with given arguments and possibility to specify return type (since C++23) (function template) | ### Identity `std::identity` is the identity function object: it returns its argument unchanged. | | | | --- | --- | | [identity](functional/identity "cpp/utility/functional/identity") (C++20) | function object that returns its argument unchanged (class) | ### Partial function application `[std::bind\_front](functional/bind_front "cpp/utility/functional/bind front")` and `[std::bind](functional/bind "cpp/utility/functional/bind")` provide support for [partial function application](https://en.wikipedia.org/wiki/Partial_application "enwiki:Partial application"), i.e. binding arguments to functions to produce new functions. | | | | --- | --- | | [bind\_frontbind\_back](functional/bind_front "cpp/utility/functional/bind front") (C++20)(C++23) | bind a variable number of arguments, in order, to a function object (function template) | | [bind](functional/bind "cpp/utility/functional/bind") (C++11) | binds one or more arguments to a function object (function template) | | [is\_bind\_expression](functional/is_bind_expression "cpp/utility/functional/is bind expression") (C++11) | indicates that an object is `std::bind` expression or can be used as one (class template) | | [is\_placeholder](functional/is_placeholder "cpp/utility/functional/is placeholder") (C++11) | indicates that an object is a standard placeholder or can be used as one (class template) | | Defined in namespace `std::placeholders` | | [\_1, \_2, \_3, \_4, ...](functional/placeholders "cpp/utility/functional/placeholders") (C++11) | placeholders for the unbound arguments in a `std::bind` expression (constant) | ### Negators `[std::not\_fn](functional/not_fn "cpp/utility/functional/not fn")` creates a function object that negates the result of the callable object passed to it. | | | | --- | --- | | [not\_fn](functional/not_fn "cpp/utility/functional/not fn") (C++17) | Creates a function object that returns the complement of the result of the function object it holds (function template) | ### Searchers Searchers implementing several string searching algorithms are provided and can be used either directly or with `[std::search](../algorithm/search "cpp/algorithm/search")`. | | | | --- | --- | | [default\_searcher](functional/default_searcher "cpp/utility/functional/default searcher") (C++17) | standard C++ library search algorithm implementation (class template) | | [boyer\_moore\_searcher](functional/boyer_moore_searcher "cpp/utility/functional/boyer moore searcher") (C++17) | Boyer-Moore search algorithm implementation (class template) | | [boyer\_moore\_horspool\_searcher](functional/boyer_moore_horspool_searcher "cpp/utility/functional/boyer moore horspool searcher") (C++17) | Boyer-Moore-Horspool search algorithm implementation (class template) | ### Reference wrappers Reference wrappers allow reference arguments to be stored in copyable function objects: | | | | --- | --- | | [reference\_wrapper](functional/reference_wrapper "cpp/utility/functional/reference wrapper") (C++11) | [CopyConstructible](../named_req/copyconstructible "cpp/named req/CopyConstructible") and [CopyAssignable](../named_req/copyassignable "cpp/named req/CopyAssignable") reference wrapper (class template) | | [refcref](functional/ref "cpp/utility/functional/ref") (C++11)(C++11) | creates a `[std::reference\_wrapper](functional/reference_wrapper "cpp/utility/functional/reference wrapper")` with a type deduced from its argument (function template) | | [unwrap\_referenceunwrap\_ref\_decay](functional/unwrap_reference "cpp/utility/functional/unwrap reference") (C++20)(C++20) | get the reference type wrapped in `[std::reference\_wrapper](functional/reference_wrapper "cpp/utility/functional/reference wrapper")` (class template) | ### Operator function objects C++ defines several function objects that represent common arithmetic and logical operations: | | | --- | | Arithmetic operations | | [plus](functional/plus "cpp/utility/functional/plus") | function object implementing `x + y` (class template) | | [minus](functional/minus "cpp/utility/functional/minus") | function object implementing `x - y` (class template) | | [multiplies](functional/multiplies "cpp/utility/functional/multiplies") | function object implementing `x * y` (class template) | | [divides](functional/divides "cpp/utility/functional/divides") | function object implementing `x / y` (class template) | | [modulus](functional/modulus "cpp/utility/functional/modulus") | function object implementing `x % y` (class template) | | [negate](functional/negate "cpp/utility/functional/negate") | function object implementing `-x` (class template) | | Comparisons | | [equal\_to](functional/equal_to "cpp/utility/functional/equal to") | function object implementing `x == y` (class template) | | [not\_equal\_to](functional/not_equal_to "cpp/utility/functional/not equal to") | function object implementing `x != y` (class template) | | [greater](functional/greater "cpp/utility/functional/greater") | function object implementing `x > y` (class template) | | [less](functional/less "cpp/utility/functional/less") | function object implementing `x < y` (class template) | | [greater\_equal](functional/greater_equal "cpp/utility/functional/greater equal") | function object implementing `x >= y` (class template) | | [less\_equal](functional/less_equal "cpp/utility/functional/less equal") | function object implementing `x <= y` (class template) | | Logical operations | | [logical\_and](functional/logical_and "cpp/utility/functional/logical and") | function object implementing `x && y` (class template) | | [logical\_or](functional/logical_or "cpp/utility/functional/logical or") | function object implementing `x || y` (class template) | | [logical\_not](functional/logical_not "cpp/utility/functional/logical not") | function object implementing `!x` (class template) | | Bitwise operations | | [bit\_and](functional/bit_and "cpp/utility/functional/bit and") | function object implementing `x & y` (class template) | | [bit\_or](functional/bit_or "cpp/utility/functional/bit or") | function object implementing `x | y` (class template) | | [bit\_xor](functional/bit_xor "cpp/utility/functional/bit xor") | function object implementing `x ^ y` (class template) | | [bit\_not](functional/bit_not "cpp/utility/functional/bit not") (C++14) | function object implementing `~x` (class template) | ### Constrained comparison function objects C++20 defines a set of [constrained](../language/constraints "cpp/language/constraints") comparison function objects. The equality operators (`ranges::equal_to` and `ranges::not_equal_to`) require the types of the arguments to model [`equality_comparable_with`](../concepts/equality_comparable "cpp/concepts/equality comparable"). The relational operators (`ranges::less`, `ranges::greater`, `ranges::less_equal`, and `ranges::greater_equal`) require the types of the arguments to model [`totally_ordered_with`](../concepts/totally_ordered "cpp/concepts/totally ordered"). The three-way comparison operator (`compare_three_way`) requires the type to model [`three_way_comparable_with`](compare/three_way_comparable "cpp/utility/compare/three way comparable"). | | | | --- | --- | | [ranges::equal\_to](functional/ranges/equal_to "cpp/utility/functional/ranges/equal to") (C++20) | function object implementing `x == y` (class) | | [ranges::not\_equal\_to](functional/ranges/not_equal_to "cpp/utility/functional/ranges/not equal to") (C++20) | function object implementing `x != y` (class) | | [ranges::less](functional/ranges/less "cpp/utility/functional/ranges/less") (C++20) | function object implementing `x < y` (class) | | [ranges::greater](functional/ranges/greater "cpp/utility/functional/ranges/greater") (C++20) | function object implementing `x > y` (class) | | [ranges::less\_equal](functional/ranges/less_equal "cpp/utility/functional/ranges/less equal") (C++20) | function object implementing `x <= y` (class) | | [ranges::greater\_equal](functional/ranges/greater_equal "cpp/utility/functional/ranges/greater equal") (C++20) | function object implementing `x >= y` (class) | | [compare\_three\_way](compare/compare_three_way "cpp/utility/compare/compare three way") (C++20) | function object implementing `x <=> y` (class) | ### Old binders and adaptors Several utilities that provided early functional support are deprecated in C++11 and removed in C++17 (old negators are deprecated in C++17 and removed in C++20): | | | --- | | Base | | [unary\_function](functional/unary_function "cpp/utility/functional/unary function") (deprecated in C++11)(removed in C++17) | adaptor-compatible unary function base class (class template) | | [binary\_function](functional/binary_function "cpp/utility/functional/binary function") (deprecated in C++11)(removed in C++17) | adaptor-compatible binary function base class (class template) | | Binders | | [binder1stbinder2nd](functional/binder12 "cpp/utility/functional/binder12") (deprecated in C++11)(removed in C++17) | function object holding a binary function and one of its arguments (class template) | | [bind1stbind2nd](functional/bind12 "cpp/utility/functional/bind12") (deprecated in C++11)(removed in C++17) | binds one argument to a binary function (function template) | | Function adaptors | | [pointer\_to\_unary\_function](functional/pointer_to_unary_function "cpp/utility/functional/pointer to unary function") (deprecated in C++11)(removed in C++17) | adaptor-compatible wrapper for a pointer to unary function (class template) | | [pointer\_to\_binary\_function](functional/pointer_to_binary_function "cpp/utility/functional/pointer to binary function") (deprecated in C++11)(removed in C++17) | adaptor-compatible wrapper for a pointer to binary function (class template) | | [ptr\_fun](functional/ptr_fun "cpp/utility/functional/ptr fun") (deprecated in C++11)(removed in C++17) | creates an adaptor-compatible function object wrapper from a pointer to function (function template) | | [mem\_fun\_tmem\_fun1\_tconst\_mem\_fun\_tconst\_mem\_fun1\_t](functional/mem_fun_t "cpp/utility/functional/mem fun t") (deprecated in C++11)(removed in C++17) | wrapper for a pointer to nullary or unary member function, callable with a pointer to object (class template) | | [mem\_fun](functional/mem_fun "cpp/utility/functional/mem fun") (deprecated in C++11)(removed in C++17) | creates a wrapper from a pointer to member function, callable with a pointer to object (function template) | | [mem\_fun\_ref\_tmem\_fun1\_ref\_tconst\_mem\_fun\_ref\_tconst\_mem\_fun1\_ref\_t](functional/mem_fun_ref_t "cpp/utility/functional/mem fun ref t") (deprecated in C++11)(removed in C++17) | wrapper for a pointer to nullary or unary member function, callable with a reference to object (class template) | | [mem\_fun\_ref](functional/mem_fun_ref "cpp/utility/functional/mem fun ref") (deprecated in C++11)(removed in C++17) | creates a wrapper from a pointer to member function, callable with a reference to object (function template) | | [unary\_negate](functional/unary_negate "cpp/utility/functional/unary negate") (deprecated in C++17)(removed in C++20) | wrapper function object returning the complement of the unary predicate it holds (class template) | | [binary\_negate](functional/binary_negate "cpp/utility/functional/binary negate") (deprecated in C++17)(removed in C++20) | wrapper function object returning the complement of the binary predicate it holds (class template) | | [not1](functional/not1 "cpp/utility/functional/not1") (deprecated in C++17)(removed in C++20) | constructs custom `[std::unary\_negate](functional/unary_negate "cpp/utility/functional/unary negate")` object (function template) | | [not2](functional/not2 "cpp/utility/functional/not2") (deprecated in C++17)(removed in C++20) | constructs custom `[std::binary\_negate](functional/binary_negate "cpp/utility/functional/binary negate")` object (function template) | cpp std::launder std::launder ============ | Defined in header `[<new>](../header/new "cpp/header/new")` | | | | --- | --- | --- | | ``` template< class T > constexpr T* launder( T* p ) noexcept; ``` | | (since C++17) (until C++20) | | ``` template< class T > [[nodiscard]] constexpr T* launder( T* p ) noexcept; ``` | | (since C++20) | Obtains a pointer to the object located at the address represented by `p`. Formally, given. * the pointer `p` represents the address `A` of a byte in memory * an object `X` is located at the address `A` * `X` is within its [lifetime](../language/lifetime "cpp/language/lifetime") * the type of `X` is the same as `T`, ignoring cv-qualifiers at every level * every byte that would be reachable through the result is reachable through p (bytes are reachable through a pointer that points to an object `Y` if those bytes are within the storage of an object `Z` that is [pointer-interconvertible](../language/static_cast#pointer-interconvertible "cpp/language/static cast") with `Y`, or within the immediately enclosing array of which `Z` is an element). Then `std::launder(p)` returns a value of type `T*` that points to the object `X`. Otherwise, the behavior is undefined. The program is ill-formed if `T` is a function type or (possibly cv-qualified) `void`. `std::launder` may be used in a [core constant expression](../language/constant_expression "cpp/language/constant expression") if and only if the (converted) value of its argument may be used in place of the function invocation. In other words, `std::launder` does not relax restrictions in constant evaluation. ### Notes `std::launder` has no effect on its argument. Its return value must be used to access the object. Thus, it's always an error to discard the return value. Typical uses of `std::launder` include: * Obtaining a pointer to an object created in the storage of an existing object of the same type, where pointers to the old object cannot be [reused](../language/lifetime#Storage_reuse "cpp/language/lifetime") (for instance, because either object is a base class subobject); * Obtaining a pointer to an object created by placement `new` from a pointer to an object providing storage for that object. The *reachability* restriction ensures that `std::launder` cannot be used to access bytes not accessible through the original pointer, thereby interfering with the compiler's escape analysis. ``` int x[10]; auto p = std::launder(reinterpret_cast<int(*)[10]>(&x[0])); // OK int x2[2][10]; auto p2 = std::launder(reinterpret_cast<int(*)[10]>(&x2[0][0])); // Undefined behavior: x2[1] would be reachable through the resulting pointer to x2[0] // but is not reachable from the source struct X { int a[10]; } x3, x4[2]; // standard layout; assume no padding auto p3 = std::launder(reinterpret_cast<int(*)[10]>(&x3.a[0])); // OK auto p4 = std::launder(reinterpret_cast<int(*)[10]>(&x4[0].a[0])); // Undefined behavior: x4[1] would be reachable through the resulting pointer to x4[0].a // (which is pointer-interconvertible with x4[0]) but is not reachable from the source struct Y { int a[10]; double y; } x5; auto p5 = std::launder(reinterpret_cast<int(*)[10]>(&x5.a[0])); // Undefined behavior: x5.y would be reachable through the resulting pointer to x5.a // but is not reachable from the source ``` ### Example ``` #include <new> #include <cstddef> #include <cassert> struct Y { int z; }; struct A { virtual int transmogrify(); }; struct B : A { int transmogrify() override { new(this) A; return 2; } }; int A::transmogrify() { new(this) B; return 1; } static_assert(sizeof(B) == sizeof(A)); int main() { // Case 1: the new object failed to be transparently replaceable because it is a // base subobject but the old object is a complete object. A i; int n = i.transmogrify(); // int m = i.transmogrify(); // undefined behavior int m = std::launder(&i)->transmogrify(); // OK assert(m + n == 3); // Case 2: access to a new object whose storage is provided by a byte array through // a pointer to the array. alignas(Y) std::byte s[sizeof(Y)]; Y* q = new(&s) Y{2}; const int f = reinterpret_cast<Y*>(&s)->z; // Class member access is undefined behavior: // reinterpret_cast<Y*>(&s) has value // "pointer to s" and does not // point to a Y object const int g = q->z; // OK const int h = std::launder(reinterpret_cast<Y*>(&s))->z; // OK [f, g, h] {}; // suppresses "unused-variable" warnings; see also [[maybe_unused]]. } ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 2859](https://cplusplus.github.io/LWG/issue2859) | C++17 | definition of *reachable* didn't consider pointer-arithmetic from pointer-interconvertible object | included | | [LWG 3495](https://cplusplus.github.io/LWG/issue3495) | C++17 | `launder` might make pointer to an inactive member dereferenceable in constant expression | forbidden |
programming_docs
cpp std::integer_sequence std::integer\_sequence ====================== | Defined in header `[<utility>](../header/utility "cpp/header/utility")` | | | | --- | --- | --- | | ``` template< class T, T... Ints > class integer_sequence; ``` | | (since C++14) | The class template `std::integer_sequence` represents a compile-time sequence of integers. When used as an argument to a [function template](../language/function_template "cpp/language/function template"), the [parameter pack](../language/parameter_pack "cpp/language/parameter pack") `Ints` can be deduced and used in pack expansion. ### Template parameters | | | | | --- | --- | --- | | T | - | an integer type to use for the elements of the sequence | | ...Ints | - | a non-type parameter pack representing the sequence | ### Member types | Member type | Definition | | --- | --- | | `value_type` | `T` | ### Member functions | | | | --- | --- | | **size** [static] | returns the number of elements in `Ints` (public static member function) | std::integer\_sequence::size ----------------------------- | | | | | --- | --- | --- | | ``` static constexpr std::size_t size() noexcept; ``` | | | Returns the number of elements in `Ints`. Equivalent to `sizeof...(Ints)`. ### Parameters (none). ### Return value The number of elements in `Ints`. ### Helper templates A helper alias template `std::index_sequence` is defined for the common case where `T` is `[std::size\_t](../types/size_t "cpp/types/size t")`: | | | | | --- | --- | --- | | ``` template<std::size_t... Ints> using index_sequence = std::integer_sequence<std::size_t, Ints...>; ``` | | | Helper alias templates `std::make_integer_sequence` and `std::make_index_sequence` are defined to simplify creation of `std::integer_sequence` and `std::index_sequence` types, respectively, with 0, 1, 2, ..., `N-1` as `Ints`: | | | | | --- | --- | --- | | ``` template<class T, T N> using make_integer_sequence = std::integer_sequence<T, /* a sequence 0, 1, 2, ..., N-1 */ >; ``` | | | | ``` template<std::size_t N> using make_index_sequence = std::make_integer_sequence<std::size_t, N>; ``` | | | The program is ill-formed if `N` is negative. If `N` is zero, the indicated type is `integer_sequence<T>`. A helper alias template `std::index_sequence_for` is defined to convert any type parameter pack into an index sequence of the same length: | | | | | --- | --- | --- | | ``` template<class... T> using index_sequence_for = std::make_index_sequence<sizeof...(T)>; ``` | | | ### Notes | [Feature-test](feature_test "cpp/utility/feature test") macro | | --- | | [`__cpp_lib_integer_sequence`](../feature_test#Library_features "cpp/feature test") | ### Example Note: see *Possible Implementation* in [`std::apply`](apply#Possible_implementation "cpp/utility/apply") for another example. ``` #include <tuple> #include <iostream> #include <array> #include <utility> // debugging aid template<typename T, T... ints> void print_sequence(std::integer_sequence<T, ints...> int_seq) { std::cout << "The sequence of size " << int_seq.size() << ": "; ((std::cout << ints << ' '), ...); std::cout << '\n'; } // convert array into a tuple template<typename Array, std::size_t... I> auto a2t_impl(const Array& a, std::index_sequence<I...>) { return std::make_tuple(a[I]...); } template<typename T, std::size_t N, typename Indices = std::make_index_sequence<N>> auto a2t(const std::array<T, N>& a) { return a2t_impl(a, Indices{}); } // pretty-print a tuple template<class Ch, class Tr, class Tuple, std::size_t... Is> void print_tuple_impl(std::basic_ostream<Ch,Tr>& os, const Tuple& t, std::index_sequence<Is...>) { ((os << (Is == 0? "" : ", ") << std::get<Is>(t)), ...); } template<class Ch, class Tr, class... Args> auto& operator<<(std::basic_ostream<Ch, Tr>& os, const std::tuple<Args...>& t) { os << "("; print_tuple_impl(os, t, std::index_sequence_for<Args...>{}); return os << ")"; } int main() { print_sequence(std::integer_sequence<unsigned, 9, 2, 5, 1, 9, 1, 6>{}); print_sequence(std::make_integer_sequence<int, 20>{}); print_sequence(std::make_index_sequence<10>{}); print_sequence(std::index_sequence_for<float, std::iostream, char>{}); std::array<int, 4> array = {1, 2, 3, 4}; // convert an array into a tuple auto tuple = a2t(array); static_assert(std::is_same_v<decltype(tuple), std::tuple<int, int, int, int>>, ""); // print it to cout std::cout << "The tuple: " << tuple << '\n'; } ``` Output: ``` The sequence of size 7: 9 2 5 1 9 1 6 The sequence of size 20: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 The sequence of size 10: 0 1 2 3 4 5 6 7 8 9 The sequence of size 3: 0 1 2 The tuple: (1, 2, 3, 4) ``` ### See also | | | | --- | --- | | [to\_array](../container/array/to_array "cpp/container/array/to array") (C++20) | creates a `std::array` object from a built-in array (function template) | cpp std::move_if_noexcept std::move\_if\_noexcept ======================= | Defined in header `[<utility>](../header/utility "cpp/header/utility")` | | | | --- | --- | --- | | ``` template< class T > typename std::conditional< !std::is_nothrow_move_constructible<T>::value && std::is_copy_constructible<T>::value, const T&, T&& >::type move_if_noexcept(T& x) noexcept; ``` | | (since C++11) (until C++14) | | ``` template< class T > constexpr typename std::conditional< !std::is_nothrow_move_constructible<T>::value && std::is_copy_constructible<T>::value, const T&, T&& >::type move_if_noexcept(T& x) noexcept; ``` | | (since C++14) | `move_if_noexcept` obtains an rvalue reference to its argument if its move constructor does not throw exceptions or if there is no copy constructor (move-only type), otherwise obtains an lvalue reference to its argument. It is typically used to combine move semantics with strong exception guarantee. ### Parameters | | | | | --- | --- | --- | | x | - | the object to be moved or copied | ### Return value `std::move(x)` or `x`, depending on exception guarantees. ### Notes This is used, for example, by `[std::vector::resize](../container/vector/resize "cpp/container/vector/resize")`, which may have to allocate new storage and then move or copy elements from old storage to new storage. If an exception occurs during this operation, `[std::vector::resize](../container/vector/resize "cpp/container/vector/resize")` undoes everything it did to this point, which is only possible if `std::move_if_noexcept` was used to decide whether to use move construction or copy construction. (unless copy constructor is not available, in which case move constructor is used either way and the strong exception guarantee may be waived). ### Example ``` #include <iostream> #include <utility> struct Bad { Bad() {} Bad(Bad&&) // may throw { std::cout << "Throwing move constructor called\n"; } Bad(const Bad&) // may throw as well { std::cout << "Throwing copy constructor called\n"; } }; struct Good { Good() {} Good(Good&&) noexcept // will NOT throw { std::cout << "Non-throwing move constructor called\n"; } Good(const Good&) noexcept // will NOT throw { std::cout << "Non-throwing copy constructor called\n"; } }; int main() { Good g; Bad b; Good g2 = std::move_if_noexcept(g); Bad b2 = std::move_if_noexcept(b); } ``` Output: ``` Non-throwing move constructor called Throwing copy constructor called ``` ### Complexity Constant. ### See also | | | | --- | --- | | [forward](forward "cpp/utility/forward") (C++11) | forwards a function argument (function template) | | [move](move "cpp/utility/move") (C++11) | obtains an rvalue reference (function template) | cpp std::in_range std::in\_range ============== | Defined in header `[<utility>](../header/utility "cpp/header/utility")` | | | | --- | --- | --- | | ``` template< class R, class T > constexpr bool in_range( T t ) noexcept; ``` | | (since C++20) | Returns `true` if the value of `t` is in the range of values that can be represented in `R`, that is, if `t` can be converted to `R` without data loss. It is a compile-time error if either `T` or `R` is not a signed or unsigned integer type (including standard integer type and extended integer type). ### Parameters | | | | | --- | --- | --- | | t | - | value to test | ### Return value `true` if the value of `t` is representable in `R`, `false` otherwise. ### Possible implementation | | | --- | | ``` template< class R, class T > constexpr bool in_range( T t ) noexcept { return std::cmp_greater_equal(t, std::numeric_limits<R>::min()) && std::cmp_less_equal(t, std::numeric_limits<R>::max()); } ``` | ### Notes This function cannot be used with [enums](../language/enum "cpp/language/enum") (including [`std::byte`](../types/byte "cpp/types/byte")), `char`, `char8_t`, `char16_t`, `char32_t`, `wchar_t` and `bool`. | [Feature-test](feature_test "cpp/utility/feature test") macro | | --- | | [`__cpp_lib_integer_comparison_functions`](../feature_test#Library_features "cpp/feature test") | ### Example ``` #include <utility> #include <iostream> int main() { std::cout << std::boolalpha; std::cout << std::in_range<std::size_t>(-1) << '\n'; std::cout << std::in_range<std::size_t>(42) << '\n'; } ``` Output: ``` false true ``` ### See also | | | | --- | --- | | [ranges::min](../algorithm/ranges/min "cpp/algorithm/ranges/min") (C++20) | returns the smaller of the given values (niebloid) | | [ranges::max](../algorithm/ranges/max "cpp/algorithm/ranges/max") (C++20) | returns the greater of the given values (niebloid) | | [ranges::clamp](../algorithm/ranges/clamp "cpp/algorithm/ranges/clamp") (C++20) | clamps a value between a pair of boundary values (niebloid) | | [lerp](../numeric/lerp "cpp/numeric/lerp") (C++20) | linear interpolation function (function) | cpp std::cmp_equal, cmp_not_equal, cmp_less, cmp_greater, cmp_less_equal, cmp_greater_equal std::cmp\_equal, cmp\_not\_equal, cmp\_less, cmp\_greater, cmp\_less\_equal, cmp\_greater\_equal ================================================================================================ | Defined in header `[<utility>](../header/utility "cpp/header/utility")` | | | | --- | --- | --- | | ``` template< class T, class U > constexpr bool cmp_equal( T t, U u ) noexcept; ``` | (1) | (since C++20) | | ``` template< class T, class U > constexpr bool cmp_not_equal( T t, U u ) noexcept; ``` | (2) | (since C++20) | | ``` template< class T, class U > constexpr bool cmp_less( T t, U u ) noexcept; ``` | (3) | (since C++20) | | ``` template< class T, class U > constexpr bool cmp_greater( T t, U u ) noexcept; ``` | (4) | (since C++20) | | ``` template< class T, class U > constexpr bool cmp_less_equal( T t, U u ) noexcept; ``` | (5) | (since C++20) | | ``` template< class T, class U > constexpr bool cmp_greater_equal( T t, U u ) noexcept; ``` | (6) | (since C++20) | Compare the values of two integers `t` and `u`. Unlike builtin comparison operators, negative signed integers always compare *less than* (and *not equal to*) unsigned integers: the comparison is safe against lossy integer conversion. ``` -1 > 0u; // true std::cmp_greater(-1, 0u); // false ``` It is a compile-time error if either `T` or `U` is not a signed or unsigned integer type (including standard integer type and extended integer type). ### Parameters | | | | | --- | --- | --- | | t | - | left-hand argument | | u | - | right-hand argument | ### Return value 1) `true` if `t` is equal to `u`. 2) `true` if `t` is not equal to `u`. 3) `true` if `t` is less than `u`. 4) `true` if `t` is greater than `u`. 5) `true` if `t` is less or equal to `u`. 6) `true` if `t` is greater or equal to `u`. ### Possible implementation | | | --- | | ``` template< class T, class U > constexpr bool cmp_equal( T t, U u ) noexcept { using UT = std::make_unsigned_t<T>; using UU = std::make_unsigned_t<U>; if constexpr (std::is_signed_v<T> == std::is_signed_v<U>) return t == u; else if constexpr (std::is_signed_v<T>) return t < 0 ? false : UT(t) == u; else return u < 0 ? false : t == UU(u); } template< class T, class U > constexpr bool cmp_not_equal( T t, U u ) noexcept { return !cmp_equal(t, u); } template< class T, class U > constexpr bool cmp_less( T t, U u ) noexcept { using UT = std::make_unsigned_t<T>; using UU = std::make_unsigned_t<U>; if constexpr (std::is_signed_v<T> == std::is_signed_v<U>) return t < u; else if constexpr (std::is_signed_v<T>) return t < 0 ? true : UT(t) < u; else return u < 0 ? false : t < UU(u); } template< class T, class U > constexpr bool cmp_greater( T t, U u ) noexcept { return cmp_less(u, t); } template< class T, class U > constexpr bool cmp_less_equal( T t, U u ) noexcept { return !cmp_greater(t, u); } template< class T, class U > constexpr bool cmp_greater_equal( T t, U u ) noexcept { return !cmp_less(t, u); } ``` | ### Notes These functions cannot be used to compare [enums](../language/enum "cpp/language/enum") (including [`std::byte`](../types/byte "cpp/types/byte")), `char`, `char8_t`, `char16_t`, `char32_t`, `wchar_t` and `bool`. | [Feature-test](feature_test "cpp/utility/feature test") macro | | --- | | [`__cpp_lib_integer_comparison_functions`](../feature_test#Library_features "cpp/feature test") | ### Example The example below might produce *different signedness comparison* warning if compiled without an appropriate warning suppression flag, e.g. `-Wno-sign-compare` (gcc/clang with `-Wall -Wextra`, see also [SO: disabling a specific warning](https://stackoverflow.com/questions/3378560)). ``` #include <utility> // Uncommenting the next line will disable "signed/unsigned comparison" warnings: // #pragma GCC diagnostic ignored "-Wsign-compare" int main() { static_assert( sizeof(int) == 4 ); // precondition // Quite surprisingly static_assert( -1 > 1U ); //< warning: sign-unsign comparison // because after implicit conversion of -1 to the RHS type (`unsigned int`) // the expression is equivalent to: static_assert( 0xFFFFFFFFU > 1U ); static_assert( 0xFFFFFFFFU == static_cast<unsigned>(-1) ); // In contrast, the cmp_* family compares integers as most expected - // negative signed integers always compare less than unsigned integers: static_assert( std::cmp_less( -1, 1U ) ); static_assert( std::cmp_less_equal( -1, 1U ) ); static_assert( ! std::cmp_greater( -1, 1U ) ); static_assert( ! std::cmp_greater_equal( -1, 1U ) ); static_assert( -1 == 0xFFFFFFFFU ); //< warning: sign-unsign comparison static_assert( std::cmp_not_equal( -1, 0xFFFFFFFFU ) ); } ``` ### See also | | | | --- | --- | | [equal\_to](functional/equal_to "cpp/utility/functional/equal to") | function object implementing `x == y` (class template) | | [not\_equal\_to](functional/not_equal_to "cpp/utility/functional/not equal to") | function object implementing `x != y` (class template) | | [less](functional/less "cpp/utility/functional/less") | function object implementing `x < y` (class template) | | [greater](functional/greater "cpp/utility/functional/greater") | function object implementing `x > y` (class template) | | [less\_equal](functional/less_equal "cpp/utility/functional/less equal") | function object implementing `x <= y` (class template) | | [greater\_equal](functional/greater_equal "cpp/utility/functional/greater equal") | function object implementing `x >= y` (class template) | | [ranges::equal\_to](functional/ranges/equal_to "cpp/utility/functional/ranges/equal to") (C++20) | function object implementing `x == y` (class) | | [ranges::not\_equal\_to](functional/ranges/not_equal_to "cpp/utility/functional/ranges/not equal to") (C++20) | function object implementing `x != y` (class) | | [ranges::less](functional/ranges/less "cpp/utility/functional/ranges/less") (C++20) | function object implementing `x < y` (class) | | [ranges::greater](functional/ranges/greater "cpp/utility/functional/ranges/greater") (C++20) | function object implementing `x > y` (class) | | [ranges::less\_equal](functional/ranges/less_equal "cpp/utility/functional/ranges/less equal") (C++20) | function object implementing `x <= y` (class) | | [ranges::greater\_equal](functional/ranges/greater_equal "cpp/utility/functional/ranges/greater equal") (C++20) | function object implementing `x >= y` (class) | | [compare\_three\_way](compare/compare_three_way "cpp/utility/compare/compare three way") (C++20) | function object implementing `x <=> y` (class) | | [in\_range](in_range "cpp/utility/in range") (C++20) | checks if an integer value is in the range of a given integer type (function template) | | [numeric\_limits](../types/numeric_limits "cpp/types/numeric limits") | provides an interface to query properties of all fundamental numeric types. (class template) | cpp std::in_place, std::in_place_type, std::in_place_index, std::in_place_t, std::in_place_type_t, std::in_place_index_t std::in\_place, std::in\_place\_type, std::in\_place\_index, std::in\_place\_t, std::in\_place\_type\_t, std::in\_place\_index\_t ================================================================================================================================= | Defined in header `[<utility>](../header/utility "cpp/header/utility")` | | | | --- | --- | --- | | ``` struct in_place_t { explicit in_place_t() = default; }; inline constexpr in_place_t in_place{}; ``` | | (since C++17) | | ``` template <class T> struct in_place_type_t { explicit in_place_type_t() = default; }; template <class T> inline constexpr in_place_type_t<T> in_place_type{}; ``` | | (since C++17) | | ``` template <std::size_t I> struct in_place_index_t { explicit in_place_index_t() = default; }; template <std::size_t I> inline constexpr in_place_index_t<I> in_place_index{}; ``` | | (since C++17) | `std::in_place`, `std::in_place_type`, and `std::in_place_index` are disambiguation tags that can be passed to the constructors of `[std::optional](optional "cpp/utility/optional")`, `[std::variant](variant "cpp/utility/variant")`, and `[std::any](any "cpp/utility/any")` to indicate that the contained object should be constructed in-place, and (for the latter two) the type of the object to be constructed. The corresponding type/type templates `std::in_place_t`, `std::in_place_type_t` and `std::in_place_index_t` can be used in the constructor's parameter list to match the intended tag. ### See also | | | | --- | --- | | [optional](optional "cpp/utility/optional") (C++17) | a wrapper that may or may not hold an object (class template) | | [variant](variant "cpp/utility/variant") (C++17) | a type-safe discriminated union (class template) | | [any](any "cpp/utility/any") (C++17) | Objects that hold instances of any [CopyConstructible](../named_req/copyconstructible "cpp/named req/CopyConstructible") type. (class) | cpp std::initializer_list std::initializer\_list ====================== (not to be confused with [member initializer list](../language/initializer_list "cpp/language/initializer list")). | Defined in header `[<initializer\_list>](../header/initializer_list "cpp/header/initializer list")` | | | | --- | --- | --- | | ``` template< class T > class initializer_list; ``` | | (since C++11) | An object of type `std::initializer_list<T>` is a lightweight proxy object that provides access to an array of objects of type `const T`. A `std::initializer_list` object is automatically constructed when: * a *braced-init-list* is used to [list-initialize](../language/list_initialization "cpp/language/list initialization") an object, where the corresponding constructor accepts an `std::initializer_list` parameter * a *braced-init-list* is used as the right operand of [assignment](../language/operator_assignment#Builtin_direct_assignment "cpp/language/operator assignment") or as a [function call argument](../language/overload_resolution#Implicit_conversion_sequence_in_list-initialization "cpp/language/overload resolution"), and the corresponding assignment operator/function accepts an `std::initializer_list` parameter * a *braced-init-list* is bound to [`auto`](../language/auto "cpp/language/auto"), including in a [ranged for loop](../language/range-for "cpp/language/range-for") Initializer lists may be implemented as a pair of pointers or pointer and length. Copying a `std::initializer_list` does not copy the underlying objects. The underlying array is a [temporary](../language/implicit_conversion#Temporary_materialization "cpp/language/implicit conversion") array of type `const T[N]`, in which each element is [copy-initialized](../language/copy_initialization "cpp/language/copy initialization") (except that narrowing conversions are invalid) from the corresponding element of the original initializer list. The lifetime of the underlying array is the same as any other [temporary object](../language/lifetime#Temporary_object_lifetime "cpp/language/lifetime"), except that initializing an initializer\_list object from the array extends the lifetime of the array exactly like [binding a reference to a temporary](../language/reference_initialization#Lifetime_of_a_temporary "cpp/language/reference initialization") (with the same exceptions, such as for initializing a non-static class member). The underlying array may be allocated in read-only memory. The program is ill-formed if an explicit or partial specialization of `std::initializer_list` is declared. ### Member types | Member type | Definition | | --- | --- | | `value_type` | `T` | | `reference` | `const T&` | | `const_reference` | `const T&` | | `size_type` | `[std::size\_t](http://en.cppreference.com/w/cpp/types/size_t)` | | `iterator` | `const T*` | | `const_iterator` | `const T*` | ### Member functions | | | | --- | --- | | [(constructor)](initializer_list/initializer_list "cpp/utility/initializer list/initializer list") | creates an empty initializer list (public member function) | | Capacity | | [size](initializer_list/size "cpp/utility/initializer list/size") | returns the number of elements in the initializer list (public member function) | | Iterators | | [begin](initializer_list/begin "cpp/utility/initializer list/begin") | returns a pointer to the first element (public member function) | | [end](initializer_list/end "cpp/utility/initializer list/end") | returns a pointer to one past the last element (public member function) | ### Non-member functions | | | | --- | --- | | [std::begin(std::initializer\_list)](initializer_list/begin2 "cpp/utility/initializer list/begin2") (C++11) | overloads `[std::begin](../iterator/begin "cpp/iterator/begin")` (function template) | | [std::end(std::initializer\_list)](initializer_list/end2 "cpp/utility/initializer list/end2") (C++11) | specializes `[std::end](../iterator/end "cpp/iterator/end")` (function template) | | Free function templates overloaded for `std::initializer_list` | | [rbegincrbegin](../iterator/rbegin "cpp/iterator/rbegin") (C++14) | returns a reverse iterator to the beginning of a container or array (function template) | | [rendcrend](../iterator/rend "cpp/iterator/rend") (C++14) | returns a reverse end iterator for a container or array (function template) | | [empty](../iterator/empty "cpp/iterator/empty") (C++17) | checks whether the container is empty (function template) | | [data](../iterator/data "cpp/iterator/data") (C++17) | obtains the pointer to the underlying array (function template) | ### Example ``` #include <iostream> #include <vector> #include <initializer_list> template <class T> struct S { std::vector<T> v; S(std::initializer_list<T> l) : v(l) { std::cout << "constructed with a " << l.size() << "-element list\n"; } void append(std::initializer_list<T> l) { v.insert(v.end(), l.begin(), l.end()); } std::pair<const T*, std::size_t> c_arr() const { return {&v[0], v.size()}; // copy list-initialization in return statement // this is NOT a use of std::initializer_list } }; template <typename T> void templated_fn(T) {} int main() { S<int> s = {1, 2, 3, 4, 5}; // copy list-initialization s.append({6, 7, 8}); // list-initialization in function call std::cout << "The vector size is now " << s.c_arr().second << " ints:\n"; for (auto n : s.v) std::cout << n << ' '; std::cout << '\n'; std::cout << "Range-for over brace-init-list: \n"; for (int x : {-1, -2, -3}) // the rule for auto makes this ranged-for work std::cout << x << ' '; std::cout << '\n'; auto al = {10, 11, 12}; // special rule for auto std::cout << "The list bound to auto has size() = " << al.size() << '\n'; // templated_fn({1, 2, 3}); // compiler error! "{1, 2, 3}" is not an expression, // it has no type, and so T cannot be deduced templated_fn<std::initializer_list<int>>({1, 2, 3}); // OK templated_fn<std::vector<int>>({1, 2, 3}); // also OK } ``` Output: ``` constructed with a 5-element list The vector size is now 8 ints: 1 2 3 4 5 6 7 8 Range-for over brace-init-list: -1 -2 -3 The list bound to auto has size() = 3 ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 1290](https://cplusplus.github.io/CWG/issues/1290.html) | C++11 | the lifetime of the underlying array referenced bythe `initializer_list` was not correctly specified | specified same as other temporary objects | | [CWG 1418](https://cplusplus.github.io/CWG/issues/1418.html) | C++11 | the type of the underlying array lacked `const` | `const` added | | [LWG 2129](https://cplusplus.github.io/LWG/issue2129) | C++11 | specializing `initializer_list` was allowedbut not guaranteed to work | made ill-formed | ### See also | | | | --- | --- | | [span](../container/span "cpp/container/span") (C++20) | a non-owning view over a contiguous sequence of objects (class template) | | [basic\_string\_view](../string/basic_string_view "cpp/string/basic string view") (C++17) | read-only string view (class template) |
programming_docs
cpp std::forward std::forward ============ | Defined in header `[<utility>](../header/utility "cpp/header/utility")` | | | | --- | --- | --- | | | (1) | | | ``` template< class T > T&& forward( typename std::remove_reference<T>::type& t ) noexcept; ``` | (since C++11) (until C++14) | | ``` template< class T > constexpr T&& forward( std::remove_reference_t<T>& t ) noexcept; ``` | (since C++14) | | | (2) | | | ``` template< class T > T&& forward( typename std::remove_reference<T>::type&& t ) noexcept; ``` | (since C++11) (until C++14) | | ``` template< class T > constexpr T&& forward( std::remove_reference_t<T>&& t ) noexcept; ``` | (since C++14) | 1) Forwards lvalues as either lvalues or as rvalues, depending on T When `t` is a [forwarding reference](../language/reference#Forwarding_references "cpp/language/reference") (a function argument that is declared as an rvalue reference to a cv-unqualified function template parameter), this overload forwards the argument to another function with the [value category](../language/value_category "cpp/language/value category") it had when passed to the calling function. For example, if used in a wrapper such as the following, the template behaves as described below: ``` template<class T> void wrapper(T&& arg) { // arg is always lvalue foo(std::forward<T>(arg)); // Forward as lvalue or as rvalue, depending on T } ``` * If a call to `wrapper()` passes an rvalue `std::string`, then `T` is deduced to `std::string` (not `std::string&`, `const std::string&`, or `std::string&&`), and `std::forward` ensures that an rvalue reference is passed to `foo`. * If a call to `wrapper()` passes a const lvalue `std::string`, then `T` is deduced to `const std::string&`, and `std::forward` ensures that a const lvalue reference is passed to `foo`. * If a call to `wrapper()` passes a non-const lvalue `std::string`, then `T` is deduced to `std::string&`, and `std::forward` ensures that a non-const lvalue reference is passed to `foo`. 2) Forwards rvalues as rvalues and prohibits forwarding of rvalues as lvalues This overload makes it possible to forward a result of an expression (such as function call), which may be rvalue or lvalue, as the original value category of a forwarding reference argument. For example, if a wrapper does not just forward its argument, but calls a member function on the argument, and forwards its result: ``` // transforming wrapper template<class T> void wrapper(T&& arg) { foo(forward<decltype(forward<T>(arg).get())>(forward<T>(arg).get())); } ``` where the type of arg may be. ``` struct Arg { int i = 1; int get() && { return i; } // call to this overload is rvalue int& get() & { return i; } // call to this overload is lvalue }; ``` Attempting to forward an rvalue as an lvalue, such as by instantiating the form (2) with lvalue reference type T, is a compile-time error. ### Notes See [template argument deduction](../language/template_argument_deduction "cpp/language/template argument deduction") for the special rules behind forwarding references (`T&&` used as a function parameter) and [forwarding references](../language/reference#Forwarding_references "cpp/language/reference") for other detail. ### Parameters | | | | | --- | --- | --- | | t | - | the object to be forwarded | ### Return value `static_cast<T&&>(t)`. ### Complexity Constant. ### Example This example demonstrates perfect forwarding of the parameter(s) to the argument of the constructor of class `T`. Also, perfect forwarding of parameter packs is demonstrated. ``` #include <iostream> #include <memory> #include <utility> struct A { A(int&& n) { std::cout << "rvalue overload, n=" << n << "\n"; } A(int& n) { std::cout << "lvalue overload, n=" << n << "\n"; } }; class B { public: template<class T1, class T2, class T3> B(T1&& t1, T2&& t2, T3&& t3) : a1_{std::forward<T1>(t1)}, a2_{std::forward<T2>(t2)}, a3_{std::forward<T3>(t3)} { } private: A a1_, a2_, a3_; }; template<class T, class U> std::unique_ptr<T> make_unique1(U&& u) { return std::unique_ptr<T>(new T(std::forward<U>(u))); } template<class T, class... U> std::unique_ptr<T> make_unique2(U&&... u) { return std::unique_ptr<T>(new T(std::forward<U>(u)...)); } int main() { auto p1 = make_unique1<A>(2); // rvalue int i = 1; auto p2 = make_unique1<A>(i); // lvalue std::cout << "B\n"; auto t = make_unique2<B>(2, i, 3); } ``` Output: ``` rvalue overload, n=2 lvalue overload, n=1 B rvalue overload, n=2 lvalue overload, n=1 rvalue overload, n=3 ``` ### See also | | | | --- | --- | | [move](move "cpp/utility/move") (C++11) | obtains an rvalue reference (function template) | | [move\_if\_noexcept](move_if_noexcept "cpp/utility/move if noexcept") (C++11) | obtains an rvalue reference if the move constructor does not throw (function template) | cpp std::piecewise_construct std::piecewise\_construct ========================= | Defined in header `[<utility>](../header/utility "cpp/header/utility")` | | | | --- | --- | --- | | ``` struct piecewise_construct_t { explicit piecewise_construct_t() = default; }; ``` | | (since C++11) | | ``` constexpr std::piecewise_construct_t piecewise_construct{}; ``` | | (since C++11) (until C++17) | | ``` inline constexpr std::piecewise_construct_t piecewise_construct{}; ``` | | (since C++17) | `std::piecewise_construct_t` is an empty class tag type used to disambiguate between different functions that take two tuple arguments. The constant `std::piecewise_construct` is an instance of it. The overloads that do not use `std::piecewise_construct_t` assume that each tuple argument becomes the element of a pair. The overloads that use `std::piecewise_construct_t` assume that each tuple argument is used to construct, piecewise, a new object of specified type, which will become the element of the pair. ### Example ``` #include <iostream> #include <utility> #include <tuple> struct Foo { Foo(std::tuple<int, float>) { std::cout << "Constructed a Foo from a tuple\n"; } Foo(int, float) { std::cout << "Constructed a Foo from an int and a float\n"; } }; int main() { std::tuple<int, float> t(1, 3.14); std::pair<Foo, Foo> p1(t, t); std::pair<Foo, Foo> p2(std::piecewise_construct, t, t); } ``` Output: ``` Constructed a Foo from a tuple Constructed a Foo from a tuple Constructed a Foo from an int and a float Constructed a Foo from an int and a float ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 2510](https://cplusplus.github.io/LWG/issue2510) | C++11 | the default constructor was non-explicit, which could lead to ambiguity | made explicit | ### See also | | | | --- | --- | | [(constructor)](pair/pair "cpp/utility/pair/pair") | constructs new pair (public member function of `std::pair<T1,T2>`) | cpp std::chars_format std::chars\_format ================== | Defined in header `[<charconv>](../header/charconv "cpp/header/charconv")` | | | | --- | --- | --- | | ``` enum class chars_format { scientific = /*unspecified*/, fixed = /*unspecified*/, hex = /*unspecified*/, general = fixed | scientific }; ``` | | (since C++17) | A [BitmaskType](../named_req/bitmasktype "cpp/named req/BitmaskType") used to specify floating-point formatting for [`std::to_chars`](to_chars "cpp/utility/to chars") and [`std::from_chars`](from_chars "cpp/utility/from chars"). ### Notes | [Feature-test](feature_test "cpp/utility/feature test") macro | | --- | | [`__cpp_lib_to_chars`](../feature_test#Library_features "cpp/feature test") | ### See also | | | | --- | --- | | [to\_chars](to_chars "cpp/utility/to chars") (C++17) | converts an integer or floating-point value to a character sequence (function) | | [from\_chars](from_chars "cpp/utility/from chars") (C++17) | converts a character sequence to an integer or floating-point value (function) | cpp std::tuple_size std::tuple\_size ================ | Defined in header `[<tuple>](../header/tuple "cpp/header/tuple")` | | | | --- | --- | --- | | Defined in header `[<array>](../header/array "cpp/header/array")` | | | | Defined in header `[<utility>](../header/utility "cpp/header/utility")` | | | | Defined in header `[<ranges>](../header/ranges "cpp/header/ranges")` | | (since C++20) | | ``` template< class T > struct tuple_size; // not defined ``` | (1) | (since C++11) | | ``` template< class T > struct tuple_size< const T > : std::integral_constant<std::size_t, std::tuple_size<T>::value> { }; ``` | (2) | (since C++11) | | ``` template< class T > struct tuple_size< volatile T > : std::integral_constant<std::size_t, std::tuple_size<T>::value> { }; ``` | (3) | (since C++11) (deprecated in C++20) | | ``` template< class T > struct tuple_size< const volatile T > : std::integral_constant<std::size_t, std::tuple_size<T>::value> { }; ``` | (4) | (since C++11) (deprecated in C++20) | Provides access to the number of elements in a tuple-like type as a compile-time constant expression. 1) The primary template is not defined. An explicit (full) or partial specialization is required to make a type tuple-like. 2-4) Specializations for a cv-qualified types reuse the `value` from the corresponding cv-unqualified versions by default. | | | | --- | --- | | `std::tuple_size` interacts with the core language: it can provide [structured binding](../language/structured_binding "cpp/language/structured binding") support in the tuple-like case. (2-4) are SFINAE-friendly: if `[std::tuple\_size](http://en.cppreference.com/w/cpp/utility/tuple/tuple_size)<T>::value` is ill-formed when treated as an unevaluated operand, they do not provide the member `value`. Access checking is performed as if in a context unrelated to `tuple_size` and `T`. Only the validity of the immediate context of the expression is considered. This allows. ``` #include <utility> struct X { int a, b; }; const auto [x, y] = X(); // structured binding declaration first attempts // tuple_size<const X> which attempts to use tuple_size<X>::value, // then soft error encountered, binds to public data members ``` | (since C++17) | ### Specializations The standard library provides following specializations for standard library types: | | | | --- | --- | | [std::tuple\_size<std::tuple>](tuple/tuple_size "cpp/utility/tuple/tuple size") (C++11) | obtains the size of `tuple` at compile time (class template specialization) | | [std::tuple\_size<std::pair>](pair/tuple_size "cpp/utility/pair/tuple size") (C++11) | obtains the size of a `pair` (class template specialization) | | [std::tuple\_size<std::array>](../container/array/tuple_size "cpp/container/array/tuple size") (C++11) | obtains the size of an `array` (class template specialization) | | [std::tuple\_size<std::ranges::subrange>](../ranges/subrange/tuple_size "cpp/ranges/subrange/tuple size") (C++20) | obtains the number of components of a `[std::ranges::subrange](../ranges/subrange "cpp/ranges/subrange")` (class template specialization) | All specializations of `std::tuple_size` satisfy [UnaryTypeTrait](../named_req/unarytypetrait "cpp/named req/UnaryTypeTrait") with *base characteristic* `[std::integral\_constant](http://en.cppreference.com/w/cpp/types/integral_constant)<[std::size\_t](http://en.cppreference.com/w/cpp/types/size_t), N>` for some `N`. Users may specialize `std::tuple_size` for program-defined types to make them tuple-like. Program-defined specializations must meet the requirements above. Usually only specialization for cv-unqualified types are needed to be customized. ### Helper variable template | Defined in header `[<tuple>](../header/tuple "cpp/header/tuple")` | | | | --- | --- | --- | | ``` template< class T > inline constexpr std::size_t tuple_size_v = tuple_size<T>::value; ``` | | (since C++17) | Inherited from [std::integral\_constant](../types/integral_constant "cpp/types/integral constant") ---------------------------------------------------------------------------------------------------- ### Member constants | | | | --- | --- | | value [static] | for a standard specialization, the number of elements in the tuple-like type `T` (public static member constant) | ### Member functions | | | | --- | --- | | operator std::size\_t | converts the object to `[std::size\_t](http://en.cppreference.com/w/cpp/types/size_t)`, returns `value` (public member function) | | operator() (C++14) | returns `value` (public member function) | ### Member types | Type | Definition | | --- | --- | | `value_type` | `std::size_t` | | `type` | `[std::integral\_constant](http://en.cppreference.com/w/cpp/types/integral_constant)<[std::size\_t](http://en.cppreference.com/w/cpp/types/size_t), value>` | ### Example ``` #include <array> #include <cstddef> #include <ranges> #include <tuple> #include <utility> template <class T, std::size_t Size> struct Arr { T data[Size]; }; // a program-defined specialization of std::tuple_size: template <class T, std::size_t Size> struct std::tuple_size<Arr<T, Size>> : public integral_constant<std::size_t, Size> {}; int main() { using tuple1 = std::tuple<int, char, double>; static_assert(3 == std::tuple_size_v<tuple1>); // uses using template (C++17) using array3x4 = std::array<std::array<int, 3>, 4>; static_assert(4 == std::tuple_size<array3x4>{}); // uses operator std::size_t using pair = std::pair<tuple1, array3x4>; static_assert(2 == std::tuple_size<pair>()); // uses operator() using sub = std::ranges::subrange<char*, char*>; static_assert(2 == std::tuple_size<sub>::value); using Arr5 = Arr<int, 5>; static_assert(5 == std::tuple_size_v<Arr5>); } ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 2212](https://cplusplus.github.io/LWG/issue2212) | C++11 | specializations for cv types were not required in some headers, which led to ambiguity | required | ### See also | | | | --- | --- | | [Structured binding](../language/structured_binding "cpp/language/structured binding") (C++17) | binds the specified names to sub-objects or tuple elements of the initializer | | [tuple\_element](tuple_element "cpp/utility/tuple element") (C++11) | obtains the element types of a tuple-like type (class template) | | [tuple\_cat](tuple/tuple_cat "cpp/utility/tuple/tuple cat") (C++11) | creates a `tuple` by concatenating any number of tuples (function template) | cpp Program support utilities Program support utilities ========================= ### Program termination The following functions manage program termination and resource cleanup. | Defined in header `[<cstdlib>](../header/cstdlib "cpp/header/cstdlib")` | | --- | | [abort](program/abort "cpp/utility/program/abort") | causes abnormal program termination (without cleaning up) (function) | | [exit](program/exit "cpp/utility/program/exit") | causes normal program termination with cleaning up (function) | | [quick\_exit](program/quick_exit "cpp/utility/program/quick exit") (C++11) | causes quick program termination without completely cleaning up (function) | | [\_Exit](program/_exit "cpp/utility/program/ Exit") (C++11) | causes normal program termination without cleaning up (function) | | [atexit](program/atexit "cpp/utility/program/atexit") | registers a function to be called on `[std::exit()](program/exit "cpp/utility/program/exit")` invocation (function) | | [at\_quick\_exit](program/at_quick_exit "cpp/utility/program/at quick exit") (C++11) | registers a function to be called on `[std::quick\_exit](program/quick_exit "cpp/utility/program/quick exit")` invocation (function) | | [EXIT\_SUCCESSEXIT\_FAILURE](program/exit_status "cpp/utility/program/EXIT status") | indicates program execution execution status (macro constant) | ### Unreachable control flow | Defined in header `[<utility>](../header/utility "cpp/header/utility")` | | --- | | [unreachable](unreachable "cpp/utility/unreachable") (C++23) | marks unreachable point of execution (function) | ### Communicating with the environment | Defined in header `[<cstdlib>](../header/cstdlib "cpp/header/cstdlib")` | | --- | | [system](program/system "cpp/utility/program/system") | calls the host environment's command processor (function) | | [getenv](program/getenv "cpp/utility/program/getenv") | access to the list of environment variables (function) | ### Signals Several functions and macro constants for signal management are provided. | Defined in header `[<csignal>](../header/csignal "cpp/header/csignal")` | | --- | | [signal](program/signal "cpp/utility/program/signal") | sets a signal handler for particular signal (function) | | [raise](program/raise "cpp/utility/program/raise") | runs the signal handler for particular signal (function) | | [sig\_atomic\_t](program/sig_atomic_t "cpp/utility/program/sig atomic t") | the integer type that can be accessed as an atomic entity from an asynchronous signal handler (typedef) | | [SIG\_DFLSIG\_IGN](program/sig_strategies "cpp/utility/program/SIG strategies") | defines signal handling strategies (macro constant) | | [SIG\_ERR](program/sig_err "cpp/utility/program/SIG ERR") | return value of [`signal`](program/signal "cpp/utility/program/signal") specifying that an error was encountered (macro constant) | | Signal types | | [SIGABRTSIGFPESIGILLSIGINTSIGSEGVSIGTERM](program/sig_types "cpp/utility/program/SIG types") | defines signal types (macro constant) | ### Non-local jumps | Defined in header `[<csetjmp>](../header/csetjmp "cpp/header/csetjmp")` | | --- | | [setjmp](program/setjmp "cpp/utility/program/setjmp") | saves the context (function macro) | | [longjmp](program/longjmp "cpp/utility/program/longjmp") | jumps to specified location (function) | | Types | | [jmp\_buf](program/jmp_buf "cpp/utility/program/jmp buf") | execution context type (typedef) | ### See also | | | --- | | [C documentation](https://en.cppreference.com/w/c/program "c/program") for Program support utilities | cpp std::forward_like std::forward\_like ================== | Defined in header `[<utility>](../header/utility "cpp/header/utility")` | | | | --- | --- | --- | | ``` template< class T, class U > [[nodiscard]] constexpr auto&& forward_like( U&& x ) noexcept; ``` | | (since C++23) | Returns a reference to `x` which has similar properties to `T&&`. The return type is determined as below: 1. If `[std::remove\_reference\_t](http://en.cppreference.com/w/cpp/types/remove_reference)<T>` is a const-qualified type, then the referenced type of the return type is `const [std::remove\_reference\_t](http://en.cppreference.com/w/cpp/types/remove_reference)<U>`. Otherwise, the referenced type is `[std::remove\_reference\_t](http://en.cppreference.com/w/cpp/types/remove_reference)<U>`. 2. If `T&&` is an lvalue reference type, then the return type is also a lvalue reference type. Otherwise, the return type is an rvalue reference type. The program is ill-formed if `T&&` is not a valid type. ### Parameters | | | | | --- | --- | --- | | x | - | a value needs to be forwarded like type `T` | ### Return value A reference to `x` of the type determined as above. ### Notes Like `[std::forward](forward "cpp/utility/forward")`, [`std::move`](move "cpp/utility/move"), and `[std::as\_const](as_const "cpp/utility/as const")`, `std::forward_like` is a type cast that only influences the [value category](../language/value_category "cpp/language/value category") of an expression, or potentially adds const-qualification. When `m` is an actual member and thus `o.m` a valid expression, this is usually spelled as `[std::forward](http://en.cppreference.com/w/cpp/utility/forward)<decltype(o)>(o).m` in C++20 code. When `o.m` is not a valid expression, i.e. members of lambda closures, one needs `std::forward_like</*see below*/>(m)`. This leads to three possible models, called *merge*, *tuple*, and *language*. * *merge*: merge the `const` qualifiers, and adopt the value category of the `Owner`. * *tuple*: what `[std::get](http://en.cppreference.com/w/cpp/utility/variant/get)<0>(Owner)` does, assuming `Owner` is a `[std::tuple](http://en.cppreference.com/w/cpp/utility/tuple)<Member>`. * *language*: what `[std::forward](http://en.cppreference.com/w/cpp/utility/forward)<decltype(Owner)>(o).m` does. The main scenario that `std::forward_like` caters to is adapting “far” objects. Neither the *tuple* nor the *language* scenarios do the right thing for that main use-case, so the *merge* model is used for `std::forward_like`. | [Feature-test](feature_test "cpp/utility/feature test") macro | | --- | | [`__cpp_lib_forward_like`](../feature_test#Library_features "cpp/feature test") | ### Possible implementation | | | --- | | ``` template<class T, class U> [[nodiscard]] constexpr auto&& forward_like(U&& x) noexcept { constexpr bool is_adding_const = std::is_const_v<std::remove_reference_t<T>>; if constexpr (std::is_lvalue_reference_v<T&&>) { if constexpr (is_adding_const) { return std::as_const(x); } else { return static_cast<U&>(x); } } else { if constexpr (is_adding_const) { return std::move(std::as_const(x)); } else { return std::move(x); } } } ``` | ### Example ``` #include <cstddef> #include <iostream> #include <memory> #include <optional> #include <type_traits> #include <utility> #include <vector> struct TypeTeller { void operator()(this auto&& self) { using SelfType = decltype(self); using UnrefSelfType = std::remove_reference_t<SelfType>; if constexpr (std::is_lvalue_reference_v<SelfType>) { if constexpr (std::is_const_v<UnrefSelfType>) std::cout << "const lvalue\n"; else std::cout << "mutable lvalue\n"; } else { if constexpr (std::is_const_v<UnrefSelfType>) std::cout << "const rvalue\n"; else std::cout << "mutable rvalue\n"; } } }; struct FarStates { std::unique_ptr<TypeTeller> ptr; std::optional<TypeTeller> opt; std::vector<TypeTeller> container; auto&& from_opt(this auto&& self) { return std::forward_like<decltype(self)>(self.opt.value()); // It is OK to use std::forward<decltype(self)>(self).opt.value(), // because std::optional provides suitable accessors. } auto&& operator[](this auto&& self, std::size_t i) { return std::forward_like<decltype(self)>(container.at(i)); // It is not so good to use std::forward<decltype(self)>(self)[i], // because containers do not provide rvalue subscript access, although they could. } auto&& from_ptr(this auto&& self) { if (!self.ptr) throw std::bad_optional_access{}; return std::forward_like<decltype(self)>(*self.ptr); // It is not good to use *std::forward<decltype(self)>(self).ptr, // because std::unique_ptr<TypeTeller> always deferences to a non-const lvalue. } }; int main() { FarStates my_state{ .ptr{std::make_unique<TypeTeller>()}, .opt{std::in_place, TypeTeller{} }, .container{std::vector<TypeTeller>(1)}, }; my_state.from_ptr(); my_state.from_opt(); my_state[0](); std::cout << '\n'; std::as_const(my_state).from_ptr(); std::as_const(my_state).from_opt(); std::as_const(my_state)[0](); std::cout << '\n'; std::move(my_state).from_ptr(); std::move(my_state).from_opt(); std::move(my_state)[0](); std::cout << '\n'; std::move(std::as_const(my_state)).from_ptr(); std::move(std::as_const(my_state)).from_opt(); std::move(std::as_const(my_state))[0](); std::cout << '\n'; } ``` Output: ``` mutable lvalue mutable lvalue mutable lvalue const lvalue const lvalue const lvalue mutable rvalue mutable rvalue mutable rvalue const rvalue const rvalue const rvalue ``` ### See also | | | | --- | --- | | [move](move "cpp/utility/move") (C++11) | obtains an rvalue reference (function template) | | [forward](forward "cpp/utility/forward") (C++11) | forwards a function argument (function template) | | [as\_const](as_const "cpp/utility/as const") (C++17) | obtains a reference to const to its argument (function template) |
programming_docs
cpp std::unreachable std::unreachable ================ | Defined in header `[<utility>](../header/utility "cpp/header/utility")` | | | | --- | --- | --- | | ``` [[noreturn]] void unreachable(); ``` | | (since C++23) | Invokes [undefined behavior](../language/ub "cpp/language/ub"). An implementation may use this to optimize impossible code branches away (typically, in optimized builds) or to trap them to prevent further execution (typically, in debug builds). ### Notes | [Feature-test](feature_test "cpp/utility/feature test") macro | Value | Std | | --- | --- | --- | | [`__cpp_lib_unreachable`](../feature_test#Library_features "cpp/feature test") | `202202L` | (C++23) | ### Possible implementation | | | --- | | ``` [[noreturn]] inline void unreachable() { // Uses compiler specific extensions if possible. // Even if no extension is used, undefined behavior is still raised by // an empty function body and the noreturn attribute. #ifdef __GNUC__ // GCC, Clang, ICC __builtin_unreachable(); #elifdef _MSC_VER // MSVC __assume(false); #endif } ``` | ### Example ``` #include <vector> #include <cassert> #include <cstddef> #include <cstdint> #include <utility> struct Color { std::uint8_t r, g, b, a; }; // Assume that only restricted set of texture caps is supported. void generate_texture(std::vector<Color>& tex, std::size_t xy) { switch (xy) { case 128: [[fallthrough]]; case 256: [[fallthrough]]; case 512: /* ... */ tex.clear(); tex.resize(xy * xy, Color{0, 0, 0, 0}); break; default: std::unreachable(); } } int main() { std::vector<Color> tex; generate_texture(tex, 128); // OK assert(tex.size() == 128 * 128); generate_texture(tex, 32); // Results in undefined behavior } ``` Possible output: ``` Segmentation fault ``` ### See also | | | --- | | [C documentation](https://en.cppreference.com/w/c/program/unreachable "c/program/unreachable") for `unreachable` | ### External Links * [GCC docs: `__builtin_unreachable`](https://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html#index-_005f_005fbuiltin_005funreachable) * [Clang docs: `__builtin_unreachable`](https://clang.llvm.org/docs/LanguageExtensions.html#builtin-unreachable) * [MSVC docs: `__assume`](https://docs.microsoft.com/en-us/cpp/intrinsics/assume) cpp std::expected std::expected ============= | Defined in header `[<expected>](../header/expected "cpp/header/expected")` | | | | --- | --- | --- | | ``` template< class T, class E > class expected; ``` | | (since C++23) | The class template `std::expected` provides a way to store either of two values. An instance of `std::expected` at any given time either holds an *expected* value of type `T`, or an *unexpected* value of type `E`. `std::expected` is never valueless. The stored value is allocated directly within the object representation of the `expected` object. No dynamic memory allocation takes place. A program is ill-formed if it instantiates an `expected` with a reference type, a function type, or a specialization of [`std::unexpected`](expected/unexpected "cpp/utility/expected/unexpected"). In addition, `T` must not be `[std::in\_place\_t](in_place "cpp/utility/in place")` or `std::unexpect_t`. ### Template parameters | | | | | --- | --- | --- | | T | - | the type of the expected value. The type must either be (possible cv-qualified) `void`, or meet the [Destructible](../named_req/destructible "cpp/named req/Destructible") requirements (in particular, array and reference types are not allowed). | | E | - | the type of the unexpected value. The type must meet the [Destructible](../named_req/destructible "cpp/named req/Destructible") requirements, and must be a valid template argument for [`std::unexpected`](expected/unexpected "cpp/utility/expected/unexpected") (in particular, arrays, non-object types, and cv-qualified types are not allowed). | ### Member types | Member type | Definition | | --- | --- | | `value_type` | `T` | | `error_type` | `E` | | `unexpected_type` | `std::unexpected<E>` | | `rebind` | ``` template< class U > using rebind = expected<U, error_type>; ``` | ### Member functions | | | | --- | --- | | [(constructor)](expected/expected "cpp/utility/expected/expected") | constructs the `expected` object (public member function) | | [(destructor)](expected/~expected "cpp/utility/expected/~expected") | destroys the `expected` object, along with its contained value (public member function) | | [operator=](expected/operator= "cpp/utility/expected/operator=") | assigns contents (public member function) | | Observers | | [operator->operator\*](expected/operator* "cpp/utility/expected/operator*") | accesses the expected value (public member function) | | [operator boolhas\_value](expected/operator_bool "cpp/utility/expected/operator bool") | checks whether the object contains an expected value (public member function) | | [value](expected/value "cpp/utility/expected/value") | returns the expected value (public member function) | | [error](expected/error "cpp/utility/expected/error") | returns the unexpected value (public member function) | | [value\_or](expected/value_or "cpp/utility/expected/value or") | returns the expected value if available, another value otherwise (public member function) | | Modifiers | | [emplace](expected/emplace "cpp/utility/expected/emplace") | constructs the expected value in-place (public member function) | | [swap](expected/swap "cpp/utility/expected/swap") | exchanges the contents (public member function) | ### Non-member functions | | | | --- | --- | | [operator==](expected/operator_cmp "cpp/utility/expected/operator cmp") (C++23) | compares `expected` objects (function template) | | [swap(std::expected)](expected/swap2 "cpp/utility/expected/swap2") (C++23) | specializes the `[std::swap](../algorithm/swap "cpp/algorithm/swap")` algorithm (function) | ### Helper classes | | | | --- | --- | | [unexpected](expected/unexpected "cpp/utility/expected/unexpected") (C++23) | represented as an unexpected value in expected (class template) | | [bad\_expected\_access](expected/bad_expected_access "cpp/utility/expected/bad expected access") (C++23) | exception indicating checked access to an expected that contains an unexpected value (class template) | | [unexpect\_t](https://en.cppreference.com/mwiki/index.php?title=cpp/utility/expected/unexpect_t&action=edit&redlink=1 "cpp/utility/expected/unexpect t (page does not exist)") (C++23) | in-place construction tag for unexpected value in expected (class) | ### Helper objects | | | | --- | --- | | [unexpect](https://en.cppreference.com/mwiki/index.php?title=cpp/utility/expected/unexpect&action=edit&redlink=1 "cpp/utility/expected/unexpect (page does not exist)") (C++23) | object of type `unexpect_t` (constant) | ### Notes | [Feature-test](feature_test "cpp/utility/feature test") macro | Value | Std | | --- | --- | --- | | [`__cpp_lib_expected`](../feature_test#Library_features "cpp/feature test") | `202202L` | (C++23) | ### Example ### See also | | | | --- | --- | | [variant](variant "cpp/utility/variant") (C++17) | a type-safe discriminated union (class template) | | [optional](optional "cpp/utility/optional") (C++17) | a wrapper that may or may not hold an object (class template) | cpp std::move std::move ========= | Defined in header `[<utility>](../header/utility "cpp/header/utility")` | | | | --- | --- | --- | | ``` template< class T > typename std::remove_reference<T>::type&& move( T&& t ) noexcept; ``` | | (since C++11) (until C++14) | | ``` template< class T > constexpr std::remove_reference_t<T>&& move( T&& t ) noexcept; ``` | | (since C++14) | `std::move` is used to *indicate* that an object `t` may be "moved from", i.e. allowing the efficient transfer of resources from `t` to another object. In particular, `std::move` produces an [xvalue expression](../language/value_category "cpp/language/value category") that identifies its argument `t`. It is exactly equivalent to a `static_cast` to an rvalue reference type. ### Parameters | | | | | --- | --- | --- | | t | - | the object to be moved | ### Return value `static\_cast<typename [std::remove\_reference](http://en.cppreference.com/w/cpp/types/remove_reference)<T>::type&&>(t)`. ### Notes The functions that accept rvalue reference parameters (including [move constructors](../language/move_constructor "cpp/language/move constructor"), [move assignment operators](../language/move_operator "cpp/language/move operator"), and regular member functions such as `[std::vector::push\_back](../container/vector/push_back "cpp/container/vector/push back")`) are selected, by [overload resolution](../language/overload_resolution "cpp/language/overload resolution"), when called with [rvalue](../language/value_category "cpp/language/value category") arguments (either [prvalues](../language/value_category "cpp/language/value category") such as a temporary object or [xvalues](../language/value_category "cpp/language/value category") such as the one produced by `std::move`). If the argument identifies a resource-owning object, these overloads have the option, but aren't required, to *move* any resources held by the argument. For example, a move constructor of a linked list might copy the pointer to the head of the list and store `nullptr` in the argument instead of allocating and copying individual nodes. Names of [rvalue reference](../language/reference "cpp/language/reference") variables are [lvalues](../language/value_category "cpp/language/value category") and have to be converted to [xvalues](../language/value_category "cpp/language/value category") to be bound to the function overloads that accept rvalue reference parameters, which is why [move constructors](../language/move_constructor "cpp/language/move constructor") and [move assignment operators](../language/move_operator "cpp/language/move operator") typically use `std::move`: ``` // Simple move constructor A(A&& arg) : member(std::move(arg.member)) // the expression "arg.member" is lvalue {} // Simple move assignment operator A& operator=(A&& other) { member = std::move(other.member); return *this; } ``` One exception is when the type of the function parameter is rvalue reference to type template parameter ("forwarding reference" or "universal reference"), in which case `[std::forward](forward "cpp/utility/forward")` is used instead. Unless otherwise specified, all standard library objects that have been moved from are placed in a "valid but unspecified state", meaning the object's class invariants hold (so functions without preconditions, such as the assignment operator, can be safely used on the object after it was moved from): ``` std::vector<std::string> v; std::string str = "example"; v.push_back(std::move(str)); // str is now valid but unspecified str.back(); // undefined behavior if size() == 0: back() has a precondition !empty() if (!str.empty()) str.back(); // OK, empty() has no precondition and back() precondition is met str.clear(); // OK, clear() has no preconditions ``` Also, the standard library functions called with xvalue arguments may assume the argument is the only reference to the object; if it was constructed from an lvalue with `std::move`, no aliasing checks are made. However, self-move-assignment of standard library types is guaranteed to place the object in a valid (but usually unspecified) state: ``` std::vector<int> v = {2, 3, 3}; v = std::move(v); // the value of v is unspecified ``` ### Example ``` #include <iomanip> #include <iostream> #include <utility> #include <vector> #include <string> int main() { std::string str = "Salut"; std::vector<std::string> v; // uses the push_back(const T&) overload, which means // we'll incur the cost of copying str v.push_back(str); std::cout << "After copy, str is " << std::quoted(str) << '\n'; // uses the rvalue reference push_back(T&&) overload, // which means no strings will be copied; instead, the contents // of str will be moved into the vector. This is less // expensive, but also means str might now be empty. v.push_back(std::move(str)); std::cout << "After move, str is " << std::quoted(str) << '\n'; std::cout << "The contents of the vector are { " << std::quoted(v[0]) << ", " << std::quoted(v[1]) << " }\n"; } ``` Possible output: ``` After copy, str is "Salut" After move, str is "" The contents of the vector are { "Salut", "Salut" } ``` ### See also | | | | --- | --- | | [forward](forward "cpp/utility/forward") (C++11) | forwards a function argument (function template) | | [move\_if\_noexcept](move_if_noexcept "cpp/utility/move if noexcept") (C++11) | obtains an rvalue reference if the move constructor does not throw (function template) | | [move](../algorithm/move "cpp/algorithm/move") (C++11) | moves a range of elements to a new location (function template) | cpp Variadic functions Variadic functions ================== Variadic functions are functions (e.g. `[std::printf](../io/c/fprintf "cpp/io/c/fprintf")`) which take a [variable number of arguments](../language/variadic_arguments "cpp/language/variadic arguments"). To declare a variadic function, an ellipsis appears after the list of parameters, e.g. `int printf(const char* format...);`, which may be preceded by an optional comma. See [Variadic arguments](../language/variadic_arguments "cpp/language/variadic arguments") for additional detail on the syntax, automatic argument conversions and the alternatives. To access the variadic arguments from the function body, the following library facilities are provided: | Defined in header `[<cstdarg>](../header/cstdarg "cpp/header/cstdarg")` | | --- | | [va\_start](variadic/va_start "cpp/utility/variadic/va start") | enables access to variadic function arguments (function macro) | | [va\_arg](variadic/va_arg "cpp/utility/variadic/va arg") | accesses the next variadic function argument (function macro) | | [va\_copy](variadic/va_copy "cpp/utility/variadic/va copy") (C++11) | makes a copy of the variadic function arguments (function macro) | | [va\_end](variadic/va_end "cpp/utility/variadic/va end") | ends traversal of the variadic function arguments (function macro) | | [va\_list](variadic/va_list "cpp/utility/variadic/va list") | holds the information needed by va\_start, va\_arg, va\_end, and va\_copy (typedef) | ### Example ``` #include <iostream> #include <cstdarg> void simple_printf(const char* fmt...) // C-style "const char* fmt, ..." is also valid { va_list args; va_start(args, fmt); while (*fmt != '\0') { if (*fmt == 'd') { int i = va_arg(args, int); std::cout << i << '\n'; } else if (*fmt == 'c') { // note automatic conversion to integral type int c = va_arg(args, int); std::cout << static_cast<char>(c) << '\n'; } else if (*fmt == 'f') { double d = va_arg(args, double); std::cout << d << '\n'; } ++fmt; } va_end(args); } int main() { simple_printf("dcff", 3, 'a', 1.999, 42.5); } ``` Output: ``` 3 a 1.999 42.5 ``` ### See also | | | --- | | [C documentation](https://en.cppreference.com/w/c/variadic "c/variadic") for Variadic functions | cpp std::exchange std::exchange ============= | Defined in header `[<utility>](../header/utility "cpp/header/utility")` | | | | --- | --- | --- | | ``` template< class T, class U = T > T exchange( T& obj, U&& new_value ); ``` | | (since C++14) (until C++20) | | ``` template< class T, class U = T > constexpr T exchange( T& obj, U&& new_value ); ``` | | (since C++20) (until C++23) | | ``` template< class T, class U = T > constexpr T exchange( T& obj, U&& new_value ) noexcept(/* see below */); ``` | | (since C++23) | Replaces the value of `obj` with `new_value` and returns the old value of `obj`. ### Parameters | | | | | --- | --- | --- | | obj | - | object whose value to replace | | new\_value | - | the value to assign to `obj` | | Type requirements | | -`T` must meet the requirements of [MoveConstructible](../named_req/moveconstructible "cpp/named req/MoveConstructible"). Also, it must be possible to move-assign objects of type `U` to objects of type `T` | ### Return value The old value of `obj`. ### Exceptions | | | | --- | --- | | (none). | (until C++23) | | [`noexcept`](../language/noexcept_spec "cpp/language/noexcept spec") specification: `noexcept( [std::is\_nothrow\_move\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_move_constructible)<T> && [std::is\_nothrow\_assignable\_v](http://en.cppreference.com/w/cpp/types/is_assignable)<T&, U> )` | (since C++23) | ### Possible implementation | | | --- | | ``` template<class T, class U = T> constexpr // since C++20 T exchange(T& obj, U&& new_value) noexcept( // since C++23 std::is_nothrow_move_constructible<T>::value && std::is_nothrow_assignable<T&, U>::value ) { T old_value = std::move(obj); obj = std::forward<U>(new_value); return old_value; } ``` | ### Notes The `std::exchange` can be used when implementing [move assignment operators](../language/move_assignment "cpp/language/move assignment") and [move constructors](../language/move_constructor "cpp/language/move constructor"): ``` struct S { int n; S(S&& other) noexcept : n{std::exchange(other.n, 0)} {} S& operator=(S&& other) noexcept { if(this != &other) n = std::exchange(other.n, 0); // move n, while leaving zero in other.n return *this; } }; ``` | [Feature-test](feature_test "cpp/utility/feature test") macro | | --- | | [`__cpp_lib_exchange_function`](../feature_test#Library_features "cpp/feature test") | ### Example ``` #include <iostream> #include <utility> #include <vector> #include <iterator> class stream { public: using flags_type = int; public: flags_type flags() const { return flags_; } // Replaces flags_ by newf, and returns the old value. flags_type flags(flags_type newf) { return std::exchange(flags_, newf); } private: flags_type flags_ = 0; }; void f() { std::cout << "f()"; } int main() { stream s; std::cout << s.flags() << '\n'; std::cout << s.flags(12) << '\n'; std::cout << s.flags() << "\n\n"; std::vector<int> v; // Since the second template parameter has a default value, it is possible // to use a braced-init-list as second argument. The expression below // is equivalent to std::exchange(v, std::vector<int>{1,2,3,4}); std::exchange(v, {1,2,3,4}); std::copy(begin(v),end(v), std::ostream_iterator<int>(std::cout,", ")); std::cout << "\n\n"; void (*fun)(); // the default value of template parameter also makes possible to use a // normal function as second argument. The expression below is equivalent to // std::exchange(fun, static_cast<void(*)()>(f)) std::exchange(fun,f); fun(); std::cout << "\n\nFibonacci sequence: "; for (int a{0}, b{1}; a < 100; a = std::exchange(b, a + b)) std::cout << a << ", "; std::cout << "...\n"; } ``` Output: ``` 0 0 12 1, 2, 3, 4, f() Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... ``` ### See also | | | | --- | --- | | [swap](../algorithm/swap "cpp/algorithm/swap") | swaps the values of two objects (function template) | | [atomic\_exchangeatomic\_exchange\_explicit](../atomic/atomic_exchange "cpp/atomic/atomic exchange") (C++11)(C++11) | atomically replaces the value of the atomic object with non-atomic argument and returns the old value of the atomic (function template) |
programming_docs
cpp std::bitset<N>::operator<<,<<=,>>,>>= std::bitset<N>::operator<<,<<=,>>,>>= ===================================== | | | | | --- | --- | --- | | | (1) | | | ``` bitset operator<<( std::size_t pos ) const; ``` | (until C++11) | | ``` bitset operator<<( std::size_t pos ) const noexcept; ``` | (since C++11) (until C++23) | | ``` constexpr bitset operator<<( std::size_t pos ) const noexcept; ``` | (since C++23) | | | (2) | | | ``` bitset& operator<<=( std::size_t pos ); ``` | (until C++11) | | ``` bitset& operator<<=( std::size_t pos ) noexcept; ``` | (since C++11) (until C++23) | | ``` constexpr bitset& operator<<=( std::size_t pos ) noexcept; ``` | (since C++23) | | | (3) | | | ``` bitset operator>>( std::size_t pos ) const; ``` | (until C++11) | | ``` bitset operator>>( std::size_t pos ) const noexcept; ``` | (since C++11) (until C++23) | | ``` constexpr bitset operator>>( std::size_t pos ) const noexcept; ``` | (since C++23) | | | (4) | | | ``` bitset& operator>>=( std::size_t pos ); ``` | (until C++11) | | ``` bitset& operator>>=( std::size_t pos ) noexcept; ``` | (since C++11) (until C++23) | | ``` constexpr constexpr bitset& operator>>=( std::size_t pos ) noexcept; ``` | (since C++23) | Performs binary shift left (towards higher index positions) and binary shift right (towards lower index positions). Zeroes are shifted in, and bits that would go to an index out of range are dropped (ignored). 1-2) Performs binary shift left. The (2) version is destructive, i.e. performs the shift to the current object. 3-4) Performs binary shift right. The (4) version is destructive, i.e. performs the shift to the current object. ### Parameters | | | | | --- | --- | --- | | pos | - | number of positions to shift the bits | ### Return value 1,3) new bitset object containing the shifted bits 2,4) `*this` ### Example ``` #include <iostream> #include <bitset> int main() { std::bitset<8> b{0b01110010}; std::cout << b << " (initial value)\n"; for (; b.any(); b >>= 1) { for (; !b.test(0); b >>= 1) { } std::cout << b << '\n'; } std::cout << b << " (final value)\n"; } ``` Output: ``` 01110010 (initial value) 00111001 00000111 00000011 00000001 00000000 (final value) ``` ### See also | | | | --- | --- | | [rotl](../../numeric/rotl "cpp/numeric/rotl") (C++20) | computes the result of bitwise left-rotation (function template) | | [rotr](../../numeric/rotr "cpp/numeric/rotr") (C++20) | computes the result of bitwise right-rotation (function template) | | [operator&=operator|=operator^=operator~](operator_logic "cpp/utility/bitset/operator logic") | performs binary AND, OR, XOR and NOT (public member function) | cpp std::bitset<N>::reset std::bitset<N>::reset ===================== | | | | | --- | --- | --- | | | (1) | | | ``` bitset& reset(); ``` | (until C++11) | | ``` bitset& reset() noexcept; ``` | (since C++11) (until C++23) | | ``` constexpr bitset& reset() noexcept; ``` | (since C++23) | | | (2) | | | ``` bitset& reset( std::size_t pos ); ``` | (until C++23) | | ``` constexpr bitset& reset( std::size_t pos ); ``` | (since C++23) | Sets bits to `false`. 1) Sets all bits to `false` 2) Sets the bit at position `pos` to `false`. ### Parameters | | | | | --- | --- | --- | | pos | - | the position of the bit to set | ### Return value `*this`. ### Exceptions 2) Throws `[std::out\_of\_range](../../error/out_of_range "cpp/error/out of range")` if `pos` does not correspond to a valid position within the bitset ### Example ``` #include <iostream> #include <bitset> int main() { std::bitset<8> b(42); std::cout << "Bitset is " << b << '\n'; b.reset(1); std::cout << "After b.reset(1): " << b << '\n'; b.reset(); std::cout << "After b.reset(): " << b << '\n'; } ``` Output: ``` Bitset is 00101010 After b.reset(1): 00101000 After b.reset(): 00000000 ``` ### See also | | | | --- | --- | | [set](set "cpp/utility/bitset/set") | sets bits to `true` or given value (public member function) | | [flip](flip "cpp/utility/bitset/flip") | toggles the values of bits (public member function) | cpp std::bitset<N>::size std::bitset<N>::size ==================== | | | | | --- | --- | --- | | ``` std::size_t size() const; ``` | | (until C++11) | | ``` constexpr std::size_t size() const noexcept; ``` | | (since C++11) | Returns the number of bits that the bitset holds. ### Parameters (none). ### Return value number of bits that the bitset holds, i.e. the template parameter `N`. ### Example ``` #include <bitset> #include <iostream> int main() { std::cout << std::bitset<0x400>().size() << '\n'; } ``` Output: ``` 1024 ``` ### See also | | | | --- | --- | | [count](count "cpp/utility/bitset/count") | returns the number of bits set to `true` (public member function) | cpp std::bitset<N>::bitset std::bitset<N>::bitset ====================== | | | | | --- | --- | --- | | | (1) | | | ``` bitset(); ``` | (until C++11) | | ``` constexpr bitset() noexcept; ``` | (since C++11) | | | (2) | | | ``` bitset( unsigned long val ); ``` | (until C++11) | | ``` constexpr bitset( unsigned long long val ) noexcept; ``` | (since C++11) | | | (3) | | | ``` template< class CharT, class Traits, class Alloc > explicit bitset( const std::basic_string<CharT,Traits,Alloc>& str, typename std::basic_string<CharT,Traits,Alloc>::size_type pos = 0, typename std::basic_string<CharT,Traits,Alloc>::size_type n = std::basic_string<CharT,Traits,Alloc>::npos ); ``` | (until C++11) | | ``` template< class CharT, class Traits, class Alloc > explicit bitset( const std::basic_string<CharT,Traits,Alloc>& str, typename std::basic_string<CharT,Traits,Alloc>::size_type pos = 0, typename std::basic_string<CharT,Traits,Alloc>::size_type n = std::basic_string<CharT,Traits,Alloc>::npos, CharT zero = CharT('0'), CharT one = CharT('1') ); ``` | (since C++11) (constexpr since C++23) | | ``` template< class CharT > explicit bitset( const CharT* str, typename std::basic_string<CharT>::size_type n = std::basic_string<CharT>::npos, CharT zero = CharT('0'), CharT one = CharT('1') ); ``` | (4) | (since C++11) (constexpr since C++23) | Constructs a new bitset from one of several optional data sources: 1) Default constructor. Constructs a bitset with all bits set to zero. 2) Constructs a bitset, initializing the first (rightmost, least significant) `M` bit positions to the corresponding bit values of `val`, where `M` is the smaller of the number of bits in an `unsigned long long` and the number of bits `N` in the bitset being constructed. If M is less than N (the bitset is longer than 32 (until C++11)64 (since C++11) bits, for typical implementations of unsigned long (since C++11)long), the remaining bit positions are initialized to zeroes. 3) Constructs a bitset using the characters in the `[std::basic\_string](../../string/basic_string "cpp/string/basic string")` `str`. An optional starting position `pos` and length `n` can be provided, as well as characters denoting alternate values for set (`one`) and unset (`zero`) bits. `Traits::eq()` is used to compare the character values. The effective length of the initializing string is `min(n, str.size() - pos)`. If `pos > str.size()`, this constructor throws `[std::out\_of\_range](../../error/out_of_range "cpp/error/out of range")`. If any characters examined in `str` are not `zero` or `one`, it throws `[std::invalid\_argument](../../error/invalid_argument "cpp/error/invalid argument")`. 4) Similar to (3), but uses a `CharT*` instead of a `[std::basic\_string](../../string/basic_string "cpp/string/basic string")`. Equivalent to ``` bitset(n == basic_string<CharT>::npos ? basic_string<CharT>(str) : basic_string<CharT>(str, n), 0, n, zero, one) ``` ### Parameters | | | | | --- | --- | --- | | val | - | number used to initialize the bitset | | str | - | string used to initialize the bitset | | pos | - | a starting offset into `str` | | n | - | number of characters to use from `str` | | one | - | alternate character for set bits in `str` | | zero | - | alternate character for unset bits in `str` | ### Exceptions 3) `[std::out\_of\_range](../../error/out_of_range "cpp/error/out of range")` if `pos > str.size()`, `[std::invalid\_argument](../../error/invalid_argument "cpp/error/invalid argument")` if any character is not one or zero 4) `[std::invalid\_argument](../../error/invalid_argument "cpp/error/invalid argument")` if any character is not one or zero ### Example ``` #include <bitset> #include <string> #include <iostream> #include <climits> int main() { // empty constructor std::bitset<8> b1; // [0,0,0,0,0,0,0,0] // unsigned long long constructor std::bitset<8> b2(42); // [0,0,1,0,1,0,1,0] std::bitset<70> bl(ULLONG_MAX); // [0,0,0,0,0,0,1,1,1,...,1,1,1] in C++11 std::bitset<8> bs(0xfff0); // [1,1,1,1,0,0,0,0] // string constructor std::string bit_string = "110010"; std::bitset<8> b3(bit_string); // [0,0,1,1,0,0,1,0] std::bitset<8> b4(bit_string, 2); // [0,0,0,0,0,0,1,0] std::bitset<8> b5(bit_string, 2, 3); // [0,0,0,0,0,0,0,1] // string constructor using custom zero/one digits std::string alpha_bit_string = "aBaaBBaB"; std::bitset<8> b6(alpha_bit_string, 0, alpha_bit_string.size(), 'a', 'B'); // [0,1,0,0,1,1,0,1] // char* constructor using custom digits std::bitset<8> b7("XXXXYYYY", 8, 'X', 'Y'); // [0,0,0,0,1,1,1,1] std::cout << "b1: " << b1 << "\nb2: " << b2 << "\nbl: " << bl << "\nbs: " << bs << "\nb3: " << b3 << "\nb4: " << b4 << "\nb5: " << b5 << "\nb6: " << b6 << "\nb7: " << b7 << '\n'; } ``` Possible output: ``` b1: 00000000 b2: 00101010 bl: 0000001111111111111111111111111111111111111111111111111111111111111111 bs: 11110000 b3: 00110010 b4: 00000010 b5: 00000001 b6: 01001101 b7: 00001111 ``` ### See also | | | | --- | --- | | [set](set "cpp/utility/bitset/set") | sets bits to `true` or given value (public member function) | | [reset](reset "cpp/utility/bitset/reset") | sets bits to `false` (public member function) | cpp std::bitset<N>::to_ullong std::bitset<N>::to\_ullong ========================== | | | | | --- | --- | --- | | ``` unsigned long long to_ullong() const ``` | | (since C++11) (until C++23) | | ``` constexpr unsigned long long to_ullong() const ``` | | (since C++23) | Converts the contents of the bitset to an `unsigned long long` integer. The first bit of the bitset corresponds to the least significant digit of the number and the last bit corresponds to the most significant digit. ### Parameters (none). ### Return value the converted integer. ### Exceptions `[std::overflow\_error](../../error/overflow_error "cpp/error/overflow error")` if the value can not be represented in `unsigned long long`. ### Example ``` #include <iostream> #include <bitset> #include <limits> int main() { std::bitset<std::numeric_limits<unsigned long long>::digits> b( 0x123456789abcdef0LL ); std::cout << b << " " << std::hex << b.to_ullong() << '\n'; b.flip(); std::cout << b << " " << b.to_ullong() << '\n'; } ``` Output: ``` 0001001000110100010101100111100010011010101111001101111011110000 123456789abcdef0 1110110111001011101010011000011101100101010000110010000100001111 edcba9876543210f ``` ### See also | | | | --- | --- | | [to\_string](to_string "cpp/utility/bitset/to string") | returns a string representation of the data (public member function) | | [to\_ulong](to_ulong "cpp/utility/bitset/to ulong") | returns an `unsigned long` integer representation of the data (public member function) | cpp std::bitset<N>::flip std::bitset<N>::flip ==================== | | | | | --- | --- | --- | | | (1) | | | ``` bitset& flip(); ``` | (until C++11) | | ``` bitset& flip() noexcept; ``` | (since C++11) (until C++23) | | ``` constexpr bitset& flip() noexcept; ``` | (since C++23) | | | (2) | | | ``` bitset& flip( std::size_t pos ); ``` | (until C++23) | | ``` constexpr bitset& flip( std::size_t pos ); ``` | (since C++23) | Flips bits, i.e. changes `true` values to `false` and `false` values to `true`. Equivalent to a logical NOT operation on part or all of the bitset. 1) Flips all bits (like `[operator~](operator_logic "cpp/utility/bitset/operator logic")`, but in-place) 2) Flips the bit at the position `pos`. ### Parameters | | | | | --- | --- | --- | | pos | - | the position of the bit to flip | ### Return value `*this`. ### Exceptions 2) throws `[std::out\_of\_range](../../error/out_of_range "cpp/error/out of range")` if `pos` does not correspond to a valid position within the bitset. ### Example ``` #include <iostream> #include <bitset> int main() { std::bitset<4> flops; std::cout << flops << '\n' << flops.flip(0) << '\n' << flops.flip(2) << '\n' << flops.flip() << '\n'; } ``` Output: ``` 0000 0001 0101 1010 ``` ### See also | | | | --- | --- | | [set](set "cpp/utility/bitset/set") | sets bits to `true` or given value (public member function) | | [reset](reset "cpp/utility/bitset/reset") | sets bits to `false` (public member function) | | [operator&=operator|=operator^=operator~](operator_logic "cpp/utility/bitset/operator logic") | performs binary AND, OR, XOR and NOT (public member function) | cpp std::bitset<N>::operator[] std::bitset<N>::operator[] ========================== | | | | | --- | --- | --- | | | (1) | | | ``` bool operator[]( std::size_t pos ) const; ``` | (until C++11) | | ``` constexpr bool operator[]( std::size_t pos ) const; ``` | (since C++11) | | | (2) | | | ``` reference operator[]( std::size_t pos ); ``` | (until C++23) | | ``` constexpr reference operator[]( std::size_t pos ); ``` | (since C++23) | Accesses the bit at position `pos`. The first version returns the value of the bit, the second version returns an object of type `[std::bitset::reference](reference "cpp/utility/bitset/reference")` that allows modification of the value. Unlike `[test()](test "cpp/utility/bitset/test")`, does not throw exceptions: the behavior is undefined if `pos` is out of bounds. ### Parameters | | | | | --- | --- | --- | | pos | - | position of the bit to return | ### Return value 1) the value of the requested bit 2) an object of type `[std::bitset::reference](reference "cpp/utility/bitset/reference")`, which allows writing to the requested bit. ### Exceptions None. ### Example ``` #include <iostream> #include <bitset> int main() { std::bitset<8> b1{0b00101010}; // binary literal for 42 for (std::size_t i = 0; i < b1.size(); ++i) { std::cout << "b1[" << i << "]: " << b1[i] << '\n'; } b1[0] = true; // modifies the first bit through bitset::reference std::cout << "After setting bit 0, b1 holds " << b1 << '\n'; } ``` Output: ``` b1[0]: 0 b1[1]: 1 b1[2]: 0 b1[3]: 1 b1[4]: 0 b1[5]: 1 b1[6]: 0 b1[7]: 0 After setting bit 0, b1 holds 00101011 ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 11](https://cplusplus.github.io/LWG/issue11) | C++98 | (1) the description was missing in the C++ standard(2) there was only the non-const overload | (1) description added(2) added the const overload | ### See also | | | | --- | --- | | [test](test "cpp/utility/bitset/test") | accesses specific bit (public member function) | cpp std::hash(std::bitset) std::hash(std::bitset) ====================== | Defined in header `[<bitset>](../../header/bitset "cpp/header/bitset")` | | | | --- | --- | --- | | ``` template<std::size_t N> struct hash<std::bitset<N>>; ``` | | (since C++11) | The template specialization of `[std::hash](../hash "cpp/utility/hash")` for `[std::bitset](http://en.cppreference.com/w/cpp/utility/bitset)<N>` allows users to obtain hashes of objects of type `[std::bitset](http://en.cppreference.com/w/cpp/utility/bitset)<N>`. ### Example The following code shows one possible output of a hash function used on several bitsets: ``` #include <bitset> #include <iostream> #include <functional> int main() { std::bitset<4> b1{0}, b2{42}; std::bitset<8> b3{0}, b4{42}; std::hash<std::bitset<4>> hash_fn4; std::hash<std::bitset<8>> hash_fn8; using bin64 = std::bitset<64>; std::cout << bin64{hash_fn4(b1)} << " = " << hash_fn4(b1) << '\n' << bin64{hash_fn4(b2)} << " = " << hash_fn4(b2) << '\n' << bin64{hash_fn8(b3)} << " = " << hash_fn8(b3) << '\n' << bin64{hash_fn8(b4)} << " = " << hash_fn8(b4) << '\n'; } ``` Possible output: ``` 0110110100001001111011100010011011010101100001100011011000011001 = 7857072875483051545 1111111101011100010110100000111000111110100000111011100011110000 = 18400681194753865968 0110110100001001111011100010011011010101100001100011011000011001 = 7857072875483051545 0101110000011100011110011010111011100110010000110100110001001101 = 6637313742931709005 ``` ### See also | | | | --- | --- | | [hash](../hash "cpp/utility/hash") (C++11) | hash function object (class template) | cpp std::bitset<N>::count std::bitset<N>::count ===================== | | | | | --- | --- | --- | | ``` std::size_t count() const; ``` | | (until C++11) | | ``` std::size_t count() const noexcept; ``` | | (since C++11) (until C++23) | | ``` constexpr std::size_t count() const noexcept; ``` | | (since C++23) | Returns the number of bits that are set to `true`. ### Parameters (none). ### Return value number of bits that are set to `true`. ### Example ``` #include <iostream> #include <bitset> int main() { std::bitset<8> b("00010010"); std::cout << "initial value: " << b << '\n'; // find the first unset bit std::size_t idx = 0; while (idx < b.size() && b.test(idx)) ++idx; // continue setting bits until half the bitset is filled while (idx < b.size() && b.count() < b.size()/2) { b.set(idx); std::cout << "setting bit " << idx << ": " << b << '\n'; while (idx < b.size() && b.test(idx)) ++idx; } } ``` Output: ``` initial value: 00010010 setting bit 0: 00010011 setting bit 2: 00010111 ``` ### See also | | | | --- | --- | | [size](size "cpp/utility/bitset/size") | returns the number of bits that the bitset holds (public member function) | | [popcount](../../numeric/popcount "cpp/numeric/popcount") (C++20) | counts the number of 1 bits in an unsigned integer (function template) | cpp operator&,|,^(std::bitset) operator&,|,^(std::bitset) ========================== | Defined in header `[<bitset>](../../header/bitset "cpp/header/bitset")` | | | | --- | --- | --- | | | (1) | | | ``` template< std::size_t N > std::bitset<N> operator&( const std::bitset<N>& lhs, const std::bitset<N>& rhs ); ``` | (until C++11) | | ``` template< std::size_t N > std::bitset<N> operator&( const std::bitset<N>& lhs, const std::bitset<N>& rhs ) noexcept; ``` | (since C++11) (until C++23) | | ``` template< std::size_t N > constexpr std::bitset<N> operator&( const std::bitset<N>& lhs, const std::bitset<N>& rhs ) noexcept; ``` | (since C++23) | | | (2) | | | ``` template< std::size_t N > std::bitset<N> operator|( const std::bitset<N>& lhs, const std::bitset<N>& rhs ); ``` | (until C++11) | | ``` template< std::size_t N > std::bitset<N> operator|( const std::bitset<N>& lhs, const std::bitset<N>& rhs ) noexcept; ``` | (since C++11) (until C++23) | | ``` template< std::size_t N > constexpr std::bitset<N> operator|( const std::bitset<N>& lhs, const std::bitset<N>& rhs ) noexcept; ``` | (since C++23) | | | (3) | | | ``` template< std::size_t N > std::bitset<N> operator^( const std::bitset<N>& lhs, const std::bitset<N>& rhs ); ``` | (until C++11) | | ``` template< std::size_t N > std::bitset<N> operator^( const std::bitset<N>& lhs, const std::bitset<N>& rhs ) noexcept; ``` | (since C++11) (until C++23) | | ``` template< std::size_t N > constexpr std::bitset<N> operator^( const std::bitset<N>& lhs, const std::bitset<N>& rhs ) noexcept; ``` | (since C++23) | Performs binary AND, OR, and XOR between two bitsets, `lhs` and `rhs`. 1) Returns a `[std::bitset](http://en.cppreference.com/w/cpp/utility/bitset)<N>` containing the result of binary AND on corresponding pairs of bits of `lhs` and `rhs`. 2) Returns a `[std::bitset](http://en.cppreference.com/w/cpp/utility/bitset)<N>` containing the result of binary OR on corresponding pairs of bits of `lhs` and `rhs`. 3) Returns a `[std::bitset](http://en.cppreference.com/w/cpp/utility/bitset)<N>` containing the result of binary XOR on corresponding pairs of bits of `lhs` and `rhs`. ### Parameters | | | | | --- | --- | --- | | lhs | - | the bitset on the left-hand side of the operator | | rhs | - | the bitset on the right-hand side of the operator | ### Return value 1) `[std::bitset](http://en.cppreference.com/w/cpp/utility/bitset)<N>(lhs) &= rhs` 2) `[std::bitset](http://en.cppreference.com/w/cpp/utility/bitset)<N>(lhs) |= rhs` 3) `[std::bitset](http://en.cppreference.com/w/cpp/utility/bitset)<N>(lhs) ^= rhs` ### Example ``` #include <bitset> #include <iostream> int main() { std::bitset<4> b1("0110"); std::bitset<4> b2("0011"); std::cout << "b1 & b2: " << (b1 & b2) << '\n'; std::cout << "b1 | b2: " << (b1 | b2) << '\n'; std::cout << "b1 ^ b2: " << (b1 ^ b2) << '\n'; } ``` Output: ``` b1 & b2: 0010 b1 | b2: 0111 b1 ^ b2: 0101 ``` ### See also | | | | --- | --- | | [operator&=operator|=operator^=operator~](operator_logic "cpp/utility/bitset/operator logic") | performs binary AND, OR, XOR and NOT (public member function) |
programming_docs
cpp std::bitset<N>::to_ulong std::bitset<N>::to\_ulong ========================= | | | | | --- | --- | --- | | ``` unsigned long to_ulong() const ``` | | (until C++23) | | ``` constexpr unsigned long to_ulong() const ``` | | (since C++23) | Converts the contents of the bitset to an `unsigned long` integer. The first bit of the bitset corresponds to the least significant digit of the number and the last bit corresponds to the most significant digit. ### Parameters (none). ### Return value the converted integer. ### Exceptions throws `[std::overflow\_error](../../error/overflow_error "cpp/error/overflow error")` if the value can not be represented in `unsigned long`. ### Example ``` #include <iostream> #include <stdexcept> #include <bitset> int main() { for (unsigned long i = 0; i < 10; ++i) { std::bitset<5> b(i); std::bitset<5> b_inverted = ~b; std::cout << i << '\t' << b << '\t' << b_inverted << '\t' << b_inverted.to_ulong() << '\n'; } std::cout << std::bitset<32>().to_string('-') << '\n'; try { std::bitset<128> x(42); std::cout << x.to_ulong() << '\n'; x.flip(); std::cout << x.to_ulong() << '\n'; // throws } catch (const std::overflow_error& ex) { std::cout << "ex: " << ex.what() << '\n'; } } ``` Possible output: ``` 0 00000 11111 31 1 00001 11110 30 2 00010 11101 29 3 00011 11100 28 4 00100 11011 27 5 00101 11010 26 6 00110 11001 25 7 00111 11000 24 8 01000 10111 23 9 01001 10110 22 -------------------------------- 42 ex: bitset to_ulong overflow error ``` ### See also | | | | --- | --- | | [to\_string](to_string "cpp/utility/bitset/to string") | returns a string representation of the data (public member function) | | [to\_ullong](to_ullong "cpp/utility/bitset/to ullong") (C++11) | returns an `unsigned long long` integer representation of the data (public member function) | cpp std::bitset<N>::to_string std::bitset<N>::to\_string ========================== | | | | | --- | --- | --- | | ``` template< class CharT, class Traits, class Alloc > std::basic_string<CharT, Traits, Allocator> to_string() const; ``` | | (until C++11) | | ``` template< class CharT = char, class Traits = std::char_traits<CharT>, class Allocator = std::allocator<CharT> > std::basic_string<CharT, Traits, Allocator> to_string( CharT zero = CharT('0'), CharT one = CharT('1') ) const; ``` | | (since C++11) (until C++23) | | ``` template< class CharT = char, class Traits = std::char_traits<CharT>, class Allocator = std::allocator<CharT> > std::basic_string<CharT, Traits, Allocator> constexpr to_string( CharT zero = CharT('0'), CharT one = CharT('1') ) const; ``` | | (since C++23) | Converts the contents of the bitset to a string. Uses `zero` to represent bits with value of `false` and `one` to represent bits with value of `true`. The resulting string contains `N` characters with the first character corresponds to the last (`N-1`th) bit and the last character corresponding to the first bit. ### Parameters | | | | | --- | --- | --- | | zero | - | character to use to represent `false` | | one | - | character to use to represent `true` | ### Return value the converted string. ### Exceptions May throw `[std::bad\_alloc](../../memory/new/bad_alloc "cpp/memory/new/bad alloc")` from the `[std::string](../../string/basic_string "cpp/string/basic string")` constructor. ### Example ``` #include <iostream> #include <bitset> int main() { std::bitset<8> b(42); std::cout << b.to_string() << '\n' << b.to_string('*') << '\n' << b.to_string('O', 'X') << '\n'; } ``` Output: ``` 00101010 **1*1*1* OOXOXOXO ``` ### See also | | | | --- | --- | | [to\_ulong](to_ulong "cpp/utility/bitset/to ulong") | returns an `unsigned long` integer representation of the data (public member function) | | [to\_ullong](to_ullong "cpp/utility/bitset/to ullong") (C++11) | returns an `unsigned long long` integer representation of the data (public member function) | cpp std::bitset<N>::reference std::bitset<N>::reference ========================= | | | | | --- | --- | --- | | ``` class reference; ``` | | | The `[std::bitset](../bitset "cpp/utility/bitset")` class includes `std::bitset::reference` as a publicly-accessible nested class. This class is used as a proxy object to allow users to interact with individual bits of a bitset, since standard C++ types (like references and pointers) are not built with enough precision to specify individual bits. The primary use of `std::bitset::reference` is to provide an l-value that can be returned from [`operator[]`](operator_at "cpp/utility/bitset/operator at"). Any reads or writes to a bitset that happen via a `std::bitset::reference` potentially read or write to the entire underlying bitset. ### Member functions | | | | --- | --- | | (constructor) | constructs the reference. Accessible only to `[std::bitset](../bitset "cpp/utility/bitset")` itself (private member function) | | **(destructor)** | destroys the reference (public member function) | | operator= | assigns a `bool` to the referenced bit (public member function) | | **operator bool** | returns the referenced bit (public member function) | | operator~ | returns inverted referenced bit (public member function) | | flip | flips the referenced bit (public member function) | std::bitset<N>::reference::~reference -------------------------------------- | | | | | --- | --- | --- | | ``` ~reference(); ``` | | (until C++23) | | ``` constexpr ~reference(); ``` | | (since C++23) | Destroys the reference. std::bitset<N>::reference::operator= ------------------------------------- | | | | | --- | --- | --- | | | (1) | | | ``` reference& operator=( bool x ); ``` | (until C++11) | | ``` reference& operator=( bool x ) noexcept; ``` | (since C++11) (until C++23) | | ``` constexpr reference& operator=( bool x ) noexcept; ``` | (since C++23) | | | (2) | | | ``` reference& operator=( const reference& x ); ``` | (until C++11) | | ``` reference& operator=( const reference& x ) noexcept; ``` | (since C++11) (until C++23) | | ``` constexpr reference& operator=( const reference& x ) noexcept; ``` | (since C++23) | Assigns a value to the referenced bit. ### Parameters | | | | | --- | --- | --- | | x | - | value to assign | ### Return value `*this`. std::bitset<N>::reference::operator bool ----------------------------------------- | | | | | --- | --- | --- | | ``` operator bool() const; ``` | | (until C++11) | | ``` operator bool() const noexcept; ``` | | (since C++11) (until C++23) | | ``` constexpr operator bool() const noexcept; ``` | | (since C++23) | Returns the value of the referenced bit. ### Parameters (none). ### Return value The referenced bit. std::bitset<N>::reference::operator~ ------------------------------------- | | | | | --- | --- | --- | | ``` bool operator~() const; ``` | | (until C++11) | | ``` bool operator~() const noexcept; ``` | | (since C++11) (until C++23) | | ``` constexpr bool operator~() const noexcept; ``` | | (since C++23) | Returns the inverse of the referenced bit. ### Parameters (none). ### Return value The inverse of the referenced bit. std::bitset<N>::reference::flip -------------------------------- | | | | | --- | --- | --- | | ``` reference& flip(); ``` | | (until C++11) | | ``` reference& flip() noexcept; ``` | | (since C++11) (until C++23) | | ``` constexpr reference& flip() noexcept; ``` | | (since C++23) | Inverts the referenced bit. ### Parameters (none). ### Return value `*this`. ### Example ``` #include <bitset> #include <iostream> int main() { std::bitset<4> bs( 0b1110 ); std::bitset<4>::reference ref = bs[2]; // auto ref = bs[2]; auto info = [&](int n) { std::cout << n << ") bs: " << bs << "; ref bit: " << ref << '\n'; }; info(1); ref = false; info(2); ref = true; info(3); ref.flip(); info(4); ref = bs[1]; // operator=( const reference& x ) info(5); std::cout << "6) ~ref bit: " << ~ref << '\n'; } ``` Output: ``` 1) bs: 1110; ref bit: 1 2) bs: 1010; ref bit: 0 3) bs: 1110; ref bit: 1 4) bs: 1010; ref bit: 0 5) bs: 1110; ref bit: 1 6) ~ref bit: 0 ``` ### See also | | | | --- | --- | | [operator[]](operator_at "cpp/utility/bitset/operator at") | accesses specific bit (public member function) | cpp std::bitset<N>::test std::bitset<N>::test ==================== | | | | | --- | --- | --- | | ``` bool test( std::size_t pos ) const; ``` | | (until C++23) | | ``` constexpr bool test( std::size_t pos ) const; ``` | | (since C++23) | Returns the value of the bit at the position `pos`. Unlike `[operator[]](operator_at "cpp/utility/bitset/operator at")`, performs a bounds check and throws `[std::out\_of\_range](../../error/out_of_range "cpp/error/out of range")` if `pos` does not correspond to a valid position in the bitset. ### Parameters | | | | | --- | --- | --- | | pos | - | position of the bit to return | ### Return value `true` if the requested bit is set, `false` otherwise. ### Exceptions `[std::out\_of\_range](../../error/out_of_range "cpp/error/out of range")` if `pos` does not correspond to a valid position within the bitset. ### Example ``` #include <iostream> #include <bitset> #include <bit> #include <cassert> #include <stdexcept> int main() { std::bitset<10> b1("1111010000"); std::size_t idx = 0; while (idx < b1.size() && !b1.test(idx)) { ++idx; } assert(static_cast<int>(idx) == std::countr_zero(b1.to_ulong())); if (idx < b1.size()) { std::cout << "first set bit at index " << idx << '\n'; } else { std::cout << "no set bits\n"; } try { if (b1.test(b1.size())) std::cout << "Expect unexpected!\n"; } catch (std::out_of_range const& ex) { std::cout << "Exception: " << ex.what() << '\n'; } } ``` Possible output: ``` first set bit at index 4 Exception: bitset::test: __position (which is 10) >= _Nb (which is 10) ``` ### See also | | | | --- | --- | | [operator[]](operator_at "cpp/utility/bitset/operator at") | accesses specific bit (public member function) | | [popcount](../../numeric/popcount "cpp/numeric/popcount") (C++20) | counts the number of 1 bits in an unsigned integer (function template) | | [has\_single\_bit](../../numeric/has_single_bit "cpp/numeric/has single bit") (C++20) | checks if a number is an integral power of two (function template) | cpp operator<<,>>(std::bitset) operator<<,>>(std::bitset) ========================== | Defined in header `[<bitset>](../../header/bitset "cpp/header/bitset")` | | | | --- | --- | --- | | ``` template< class CharT, class Traits, std::size_t N > std::basic_ostream<CharT, Traits>& operator<<( std::basic_ostream<CharT, Traits>& os, const std::bitset<N>& x ); ``` | (1) | | | ``` template< class CharT, class Traits, std::size_t N > std::basic_istream<CharT, Traits>& operator>>( std::basic_istream<CharT, Traits>& is, std::bitset<N>& x ); ``` | (2) | | Inserts or extracts a bitset from a character stream. 1) Writes the bitset `x` to the character stream `os` as if by first converting it to a `[std::basic\_string](http://en.cppreference.com/w/cpp/string/basic_string)<CharT,Traits>` using `[to\_string()](to_string "cpp/utility/bitset/to string")`, and then writing it into `os` using the [`operator<<`](../../string/basic_string/operator_ltltgtgt "cpp/string/basic string/operator ltltgtgt") (which is a [FormattedOutputFunction](../../named_req/formattedoutputfunction "cpp/named req/FormattedOutputFunction") for strings). The characters to use for ones and zeroes are obtained from the currently-imbued locale by calling `[std::use\_facet](http://en.cppreference.com/w/cpp/locale/use_facet)<[std::ctype](http://en.cppreference.com/w/cpp/locale/ctype)<CharT>>(os.getloc()).widen()` with `'1'` and `'0'` as arguments. 2) Behaves as a [FormattedInputFunction](../../named_req/formattedinputfunction "cpp/named req/FormattedInputFunction"). After constructing and checking the sentry object, which may skip leading whitespace, extracts up to `N` characters from `is` and stores the characters in the bitset `x`. Characters are extracted until either. * `N` characters have been read, * end-of-file occurs in `is`, or * the next character is neither `is.widen('0')` nor `is.widen('1')`. If `N > 0` and no characters are extracted, `is.setstate(ios_base::failbit)` is called. ### Parameters | | | | | --- | --- | --- | | os | - | the character stream to write to | | is | - | the character stream to read from | | x | - | the bitset to be read or written | ### Return value The character stream that was operated on, e.g. `os` or `is`. ### Example ``` #include <bitset> #include <iostream> #include <sstream> int main() { std::string bit_string = "001101"; std::istringstream bit_stream(bit_string); std::bitset<3> b1; bit_stream >> b1; // reads "001", stream still holds "101" std::cout << b1 << '\n'; std::bitset<8> b2; bit_stream >> b2; // reads "101", populates the 8-bit set as "00000101" std::cout << b2 << '\n'; } ``` Output: ``` 001 00000101 ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 3199](https://cplusplus.github.io/LWG/issue3199) | C++98 | extracting a `std::bitset<0>` always set `failbit` | such extraction never sets `failbit` | ### See also | | | | --- | --- | | [operator<<=operator>>=operator<<operator>>](operator_ltltgtgt "cpp/utility/bitset/operator ltltgtgt") | performs binary shift left and shift right (public member function) | cpp std::bitset<N>::set std::bitset<N>::set =================== | | | | | --- | --- | --- | | | (1) | | | ``` bitset& set(); ``` | (until C++11) | | ``` bitset& set() noexcept; ``` | (since C++11) (until C++23) | | ``` constexpr bitset& set() noexcept; ``` | (since C++23) | | | (2) | | | ``` bitset& set( std::size_t pos, bool value = true ); ``` | (until C++23) | | ``` constexpr bitset& set( std::size_t pos, bool value = true ); ``` | (since C++23) | Sets all bits to `true` or to specified value. 1) Sets all bits to `true`. 2) Sets the bit at position `pos` to the value `value`. ### Parameters | | | | | --- | --- | --- | | pos | - | the position of the bit to set (least significant to most significant) | | value | - | the value to set the bit to | ### Return value `*this`. ### Exceptions 2) Throws `[std::out\_of\_range](../../error/out_of_range "cpp/error/out of range")` if `pos` does not correspond to a valid position within the bitset. ### Example ``` #include <iostream> #include <bitset> int main() { std::bitset<8> b; std::cout << b << '\n'; std::cout << b.set() << '\n'; std::cout << b.reset() << '\n'; for (size_t i = 1; i < b.size(); i += 2) { b.set(i); } std::cout << b << '\n'; } ``` Output: ``` 00000000 11111111 00000000 10101010 ``` ### See also | | | | --- | --- | | [reset](reset "cpp/utility/bitset/reset") | sets bits to `false` (public member function) | | [flip](flip "cpp/utility/bitset/flip") | toggles the values of bits (public member function) | cpp std::bitset<N>::operator==, std::bitset<N>::operator!= std::bitset<N>::operator==, std::bitset<N>::operator!= ====================================================== | | | | | --- | --- | --- | | | (1) | | | ``` bool operator==( const bitset& rhs ) const; ``` | (until C++11) | | ``` bool operator==( const bitset& rhs ) const noexcept; ``` | (since C++11) (until C++23) | | ``` constexpr bool operator==( const bitset& rhs ) const noexcept; ``` | (since C++23) | | | (2) | | | ``` bool operator!=( const bitset& rhs ) const; ``` | (until C++11) | | ``` bool operator!=( const bitset& rhs ) const noexcept; ``` | (since C++11) (until C++20) | 1) Returns true if all of the bits in `*this` and `rhs` are equal. 2) Returns true if any of the bits in `*this` and `rhs` are not equal. | | | | --- | --- | | The `!=` operator is [synthesized](../../language/operators#Relational_operators "cpp/language/operators") from `operator==`. | (since C++20) | ### Parameters | | | | | --- | --- | --- | | rhs | - | bitset to compare | ### Return value 1) `true` if the value of each bit in `*this` equals the value of the corresponding bit in `rhs`, otherwise `false` 2) `true` if `!(*this == rhs)`, otherwise `false` ### Example Compare given bitsets to determine if they are identical: ``` #include <iostream> #include <bitset> int main() { std::bitset<4> b1( 0b0011 ); std::bitset<4> b2( b1 ); std::bitset<4> b3( 0b0100 ); std::cout << std::boolalpha; std::cout << "b1 == b2: " << (b1 == b2) << '\n'; std::cout << "b1 == b3: " << (b1 == b3) << '\n'; std::cout << "b1 != b3: " << (b1 != b3) << '\n'; // b1 == std::bitset<3>{}; // compile-time error: incompatible types } ``` Output: ``` b1 == b2: true b1 == b3: false b1 != b3: true ``` cpp std::bitset<N>::all, std::bitset<N>::any, std::bitset<N>::none std::bitset<N>::all, std::bitset<N>::any, std::bitset<N>::none ============================================================== | | | | | --- | --- | --- | | | (1) | | | ``` bool all() const noexcept; ``` | (until C++23) | | ``` constexpr bool all() const noexcept; ``` | (since C++23) | | | (2) | | | ``` bool any() const; ``` | (until C++11) | | ``` bool any() const noexcept; ``` | (since C++11) (until C++23) | | ``` constexpr bool any() const noexcept; ``` | (since C++23) | | | (3) | | | ``` bool none() const; ``` | (until C++11) | | ``` bool none() const noexcept; ``` | (since C++11) (until C++23) | | ``` constexpr bool none() const noexcept; ``` | (since C++23) | Checks if all, any or none of the bits are set to `true`. 1) Checks if all bits are set to `true` 2) Checks if any bits are set to `true` 3) Checks if none of the bits are set to `true` ### Parameters (none). ### Return value 1) `true` if all bits are set to `true`, otherwise `false` 2) `true` if any of the bits are set to `true`, otherwise `false` 3) `true` if none of the bits are set to `true`, otherwise `false` ### Example ``` #include <iostream> #include <bitset> int main() { std::bitset<4> b1("0000"); std::bitset<4> b2("0101"); std::bitset<4> b3("1111"); std::cout << "bitset\t" << "all\t" << "any\t" << "none\n" << b1 << '\t' << b1.all() << '\t' << b1.any() << '\t' << b1.none() << '\n' << b2 << '\t' << b2.all() << '\t' << b2.any() << '\t' << b2.none() << '\n' << b3 << '\t' << b3.all() << '\t' << b3.any() << '\t' << b3.none() << '\n'; } ``` Output: ``` bitset all any none 0000 0 0 1 0101 0 1 0 1111 1 1 0 ``` ### See also | | | | --- | --- | | [count](count "cpp/utility/bitset/count") | returns the number of bits set to `true` (public member function) | | [popcount](../../numeric/popcount "cpp/numeric/popcount") (C++20) | counts the number of 1 bits in an unsigned integer (function template) |
programming_docs
cpp std::ranges::swap std::ranges::swap ================= | Defined in header `[<concepts>](../../header/concepts "cpp/header/concepts")` | | | | --- | --- | --- | | ``` namespace ranges { inline namespace /* unspecified */ { inline constexpr /* unspecified */ swap = /* unspecified */; } } ``` | | (since C++20) (customization point object) | | Call signature | | | | ``` template< class T, class U > constexpr void ranges::swap(T&& t, U&& u) noexcept(/* see below */); ``` | | | Exchanges the values referenced by `t` and `u`. `ranges::swap(t, u)` is expression-equivalent to: 1. `(void)swap(t, u)`, if `[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<T>` or `[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<U>` are class or enumeration types, and that expression is valid, where the [overload resolution](../../language/overload_resolution "cpp/language/overload resolution") is performed within namespace `std::ranges` with the additional candidate: * `template<class T> void swap(T&, T&) = delete;` If the function selected by overload resolution does not exchange the values referenced by `t` and `u`, the program is ill-formed; no diagnostic required. 2. Otherwise, `(void)[ranges::swap\_ranges](http://en.cppreference.com/w/cpp/algorithm/ranges/swap_ranges)(t, u)`, if `t` and `u` are lvalue arrays of equal extent (but possibly different element types) and `[ranges::swap](http://en.cppreference.com/w/cpp/ranges-utility-placeholder/swap)(\*t, \*u)` is a valid expression, except that `noexcept([ranges::swap](http://en.cppreference.com/w/cpp/ranges-utility-placeholder/swap)(t, u))` is equal to `noexcept([ranges::swap](http://en.cppreference.com/w/cpp/ranges-utility-placeholder/swap)(\*t, \*u))`. 3. Otherwise, exchanges the referenced values as if by `V v(std::move(t)); t = std::move(u); u = std::move(v);` if `t` and `u` are both lvalues of the same type `V` that satisfies `[std::move\_constructible](http://en.cppreference.com/w/cpp/concepts/move_constructible)<V>` and `[std::assignable\_from](http://en.cppreference.com/w/cpp/concepts/assignable_from)<V&, V>`, in which case `noexcept([ranges::swap](http://en.cppreference.com/w/cpp/ranges-utility-placeholder/swap)(t, u))` is equal to `[std::is\_nothrow\_move\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_move_constructible)<V> && [std::is\_nothrow\_move\_assignable\_v](http://en.cppreference.com/w/cpp/types/is_move_assignable)<V>`. `[ranges::swap](http://en.cppreference.com/w/cpp/ranges-utility-placeholder/swap)(t, u)` is a constant expression if `V(std::move(t))`, `V(std::move(u))`, `t = std::move(u)`, and `u = std::move(t);` are all constant expressions 4. Otherwise, `[ranges::swap](http://en.cppreference.com/w/cpp/ranges-utility-placeholder/swap)(t, u)` is ill-formed, which can result in [substitution failure](../../language/sfinae "cpp/language/sfinae") when `[ranges::swap](http://en.cppreference.com/w/cpp/ranges-utility-placeholder/swap)(t, u)` appears in the immediate context of a template instantiation. ### Expression-equivalent Expression `e` is *expression-equivalent* to expression `f`, if. * `e` and `f` have the same effects, and * either both are [constant subexpressions](../../language/constant_expression "cpp/language/constant expression") or else neither is a constant subexpression, and * either both are [potentially-throwing](../../language/noexcept_spec "cpp/language/noexcept spec") or else neither is potentially-throwing (i.e. `noexcept(e) == noexcept(f)`). ### Customization point objects The name `ranges::swap` denotes a *customization point object*, which is a const [function object](../../named_req/functionobject "cpp/named req/FunctionObject") of a [literal](../../named_req/literaltype "cpp/named req/LiteralType") [`semiregular`](../../concepts/semiregular "cpp/concepts/semiregular") class type. For exposition purposes, the cv-unqualified version of its type is denoted as `*\_\_swap\_fn*`. All instances of `*\_\_swap\_fn*` are equal. The effects of invoking different instances of type `*\_\_swap\_fn*` on the same arguments are equivalent, regardless of whether the expression denoting the instance is an lvalue or rvalue, and is const-qualified or not (however, a volatile-qualified instance is not required to be invocable). Thus, `ranges::swap` can be copied freely and its copies can be used interchangeably. Given a set of types `Args...`, if `[std::declval](http://en.cppreference.com/w/cpp/utility/declval)<Args>()...` meet the requirements for arguments to `ranges::swap` above, `*\_\_swap\_fn*` models . * `[std::invocable](http://en.cppreference.com/w/cpp/concepts/invocable)<__swap_fn, Args...>`, * `[std::invocable](http://en.cppreference.com/w/cpp/concepts/invocable)<const __swap_fn, Args...>`, * `[std::invocable](http://en.cppreference.com/w/cpp/concepts/invocable)<__swap_fn&, Args...>`, and * `[std::invocable](http://en.cppreference.com/w/cpp/concepts/invocable)<const __swap_fn&, Args...>`. Otherwise, no function call operator of `*\_\_swap\_fn*` participates in overload resolution. ### Example ``` #include <array> #include <concepts> #include <iostream> #include <ranges> #include <string_view> #include <vector> void print(std::string_view name, std::ranges::common_range auto const& p, std::ranges::common_range auto const& q) { std::cout << name << "1{ "; for (auto const& i : p) std::cout << i << ' '; std::cout << "}, " << name << "2{ "; for (auto const& i : q) std::cout << i << ' '; std::cout << "}\n"; } void print(std::string_view name, int p, int q) { std::cout << name << "1 = " << p << ", " << name << "2 = " << q << '\n'; } struct IntLike { int v; }; void swap(IntLike& lhs, int& rhs) { std::swap(lhs.v, rhs); } void swap(int& lhs, IntLike& rhs) { std::swap(lhs, rhs.v); } std::ostream& operator<<(std::ostream& out, IntLike i) { return out << i.v; } int main() { std::vector a1{10,11,12}, a2{13,14}; std::ranges::swap(a1, a2); print("a", a1, a2); std::array b1{15,16,17}, b2{18,19,20}; std::ranges::swap(b1, b2); print("b", b1, b2); // std::array c1{1,2,3}; std::array c2{4,5}; // std::ranges::swap(c1, c2); // error: no swap found by ADL int d1[]{21,22,23}, d2[]{24,25,26}; std::ranges::swap(d1, d2); print("d", d1, d2); // int e1[]{1,2,3}, e2[]{4,5}; // std::ranges::swap(e1, e2); // error: extents mismatch // char f1[]{1,2,3}; // int f2[]{4,5,6}; // std::ranges::swap(f1, f2); // error: no swap(*f1, *f2) found by ADL IntLike g1[]{1,2,3}; int g2[]{4,5,6}; std::ranges::swap(g1, g2); // heterogeneous swap supported print("g", g1, g2); int h1{27}, h2{28}; std::ranges::swap(h1, h2); print("h", h1, h2); } ``` Output: ``` a1{ 13 14 }, a2{ 10 11 12 } b1{ 18 19 20 }, b2{ 15 16 17 } d1{ 24 25 26 }, d2{ 21 22 23 } g1{ 4 5 6 }, g2{ 1 2 3 } h1 = 28, h2 = 27 ``` ### See also | | | | --- | --- | | [swappableswappable\_with](../../concepts/swappable "cpp/concepts/swappable") (C++20) | specifies that a type can be swapped or that two types can be swapped with each other (concept) | | [swap](../../algorithm/swap "cpp/algorithm/swap") | swaps the values of two objects (function template) | cpp std::rel_ops::operator!=,>,<=,>= std::rel\_ops::operator!=,>,<=,>= ================================= | Defined in header `[<utility>](../../header/utility "cpp/header/utility")` | | | | --- | --- | --- | | ``` template< class T > bool operator!=( const T& lhs, const T& rhs ); ``` | (1) | (deprecated in C++20) | | ``` template< class T > bool operator>( const T& lhs, const T& rhs ); ``` | (2) | (deprecated in C++20) | | ``` template< class T > bool operator<=( const T& lhs, const T& rhs ); ``` | (3) | (deprecated in C++20) | | ``` template< class T > bool operator>=( const T& lhs, const T& rhs ); ``` | (4) | (deprecated in C++20) | Given a user-defined `operator==` and `operator<` for objects of type `T`, implements the usual semantics of other comparison operators. 1) Implements `operator!=` in terms of `operator==`. 2) Implements `operator>` in terms of `operator<`. 3) Implements `operator<=` in terms of `operator<`. 4) Implements `operator>=` in terms of `operator<`. ### Parameters | | | | | --- | --- | --- | | lhs | - | left-hand argument | | rhs | - | right-hand argument | ### Return value 1) Returns `true` if `lhs` is *not equal* to `rhs`. 2) Returns `true` if `lhs` is *greater* than `rhs`. 3) Returns `true` if `lhs` is *less or equal* to `rhs`. 4) Returns `true` if `lhs` is *greater or equal* to `rhs`. ### Possible implementation | First version | | --- | | ``` namespace rel_ops { template< class T > bool operator!=( const T& lhs, const T& rhs ) { return !(lhs == rhs); } } ``` | | Second version | | ``` namespace rel_ops { template< class T > bool operator>( const T& lhs, const T& rhs ) { return rhs < lhs; } } ``` | | Third version | | ``` namespace rel_ops { template< class T > bool operator<=( const T& lhs, const T& rhs ) { return !(rhs < lhs); } } ``` | | Fourth version | | ``` namespace rel_ops { template< class T > bool operator>=( const T& lhs, const T& rhs ) { return !(lhs < rhs); } } ``` | ### Notes [Boost.operators](http://www.boost.org/doc/libs/release/libs/utility/operators.htm) provides a more versatile alternative to `std::rel_ops`. As of C++20, `std::rel_ops` are deprecated in favor of [`operator<=>`](../../language/default_comparisons "cpp/language/default comparisons"). ### Example ``` #include <iostream> #include <utility> struct Foo { int n; }; bool operator==(const Foo& lhs, const Foo& rhs) { return lhs.n == rhs.n; } bool operator<(const Foo& lhs, const Foo& rhs) { return lhs.n < rhs.n; } int main() { Foo f1 = {1}; Foo f2 = {2}; using namespace std::rel_ops; std::cout << std::boolalpha; std::cout << "not equal? : " << (f1 != f2) << '\n'; std::cout << "greater? : " << (f1 > f2) << '\n'; std::cout << "less equal? : " << (f1 <= f2) << '\n'; std::cout << "greater equal? : " << (f1 >= f2) << '\n'; } ``` Output: ``` not equal? : true greater? : false less equal? : true greater equal? : false ``` cpp std::stacktrace_entry::source_line std::stacktrace\_entry::source\_line ==================================== | | | | | --- | --- | --- | | ``` std::uint_least32_t source_line() const; ``` | | (since C++23) | Returns a 1-based line number that lexically relates to the evaluation represented by `*this`, or 0 on failure other than allocation failure, e.g. when `*this` is empty. Either [`source_file`](source_file "cpp/utility/stacktrace entry/source file") returns the presumed source file name and `source_line` returns the presumed line number, or [`source_file`](source_file "cpp/utility/stacktrace entry/source file") returns the actual source file name and `source_line` returns the actual line number. ### Parameters (none). ### Return value The line number specified above on success, 0 on failure other than allocation failure. ### Exceptions Throws `[std::bad\_alloc](../../memory/new/bad_alloc "cpp/memory/new/bad alloc")` if memory for the internal data structures cannot be allocated. ### Notes The presumed line number is what the predefined macro [`__LINE__`](../../preprocessor/replace "cpp/preprocessor/replace") expands to, and can be changed by the [`#line`](../../preprocessor/line "cpp/preprocessor/line") directive. This function is not required to be `noexcept` because getting source line requires allocation on some platforms. ### Example ### See also | | | | --- | --- | | [line](../source_location/line "cpp/utility/source location/line") | return the line number represented by this object (public member function of `std::source_location`) | cpp std::stacktrace_entry::stacktrace_entry std::stacktrace\_entry::stacktrace\_entry ========================================= | | | | | --- | --- | --- | | ``` constexpr stacktrace_entry() noexcept; ``` | (1) | (since C++23) | | ``` constexpr stacktrace_entry( const stacktrace_entry& other ) noexcept; ``` | (2) | (since C++23) | 1) Default constructor. Creates an empty `stacktrace_entry`. 2) Copy constructor. Creates a copy of `other`. ### Parameters | | | | | --- | --- | --- | | other | - | another `stacktrace_entry` to copy from | ### Notes A non-empty `stacktrace_entry` can be obtained from a `std::basic_stacktrace` created by `std::basic_stacktrace::current` or a copy of such `std::basic_stacktrace`. ### Example ### See also | | | | --- | --- | | [(constructor)](../source_location/source_location "cpp/utility/source location/source location") | constructs a new `source_location` with implementation-defined values (public member function of `std::source_location`) | cpp std::operator<<(std::stacktrace_entry) std::operator<<(std::stacktrace\_entry) ======================================= | Defined in header `[<stacktrace>](../../header/stacktrace "cpp/header/stacktrace")` | | | | --- | --- | --- | | ``` template< class CharT, class Traits > std::basic_ostream<CharT, Traits>& operator<<( std::basic_ostream<CharT, Traits>& os, const std::stacktrace_entry& f ); ``` | | (since C++23) | Inserts the description of `f` into the output stream `os`. Equivalent to `return os << [std::to\_string](http://en.cppreference.com/w/cpp/string/basic_string/to_string)(f);`. ### Parameters | | | | | --- | --- | --- | | os | - | an output stream | | f | - | a `stacktrace_entry` whose description is to be inserted | ### Return value `os`. ### Exceptions May throw implementation-defined exceptions. ### Notes Since `[std::string](../../string/basic_string "cpp/string/basic string")` can only be outputted by `[std::ostream](../../io/basic_ostream "cpp/io/basic ostream")` (not by e.g. `[std::wostream](../../io/basic_ostream "cpp/io/basic ostream")`), it is effectively required that `os` be of type `[std::ostream](http://en.cppreference.com/w/cpp/io/basic_ostream)&`. ### Example ``` #include <stacktrace> #include <iostream> int main() { for (const auto &f : std::stacktrace::current()) std::cout << f << '\n'; } ``` Possible output: ``` 0x0000000000402AA7 in ./prog.exe __libc_start_main in /lib/x86_64-linux-gnu/libc.so.6 0x00000000004029B9 in ./prog.exe ``` ### See also | | | | --- | --- | | [operator<<](../basic_stacktrace/operator_ltlt "cpp/utility/basic stacktrace/operator ltlt") (C++23) | performs stream output of `basic_stracktrace` (function template) | cpp std::hash(std::stacktrace_entry) std::hash(std::stacktrace\_entry) ================================= | Defined in header `[<stacktrace>](../../header/stacktrace "cpp/header/stacktrace")` | | | | --- | --- | --- | | ``` template<> struct hash<std::stacktrace_entry>; ``` | | (since C++23) | The template specialization of `[std::hash](../hash "cpp/utility/hash")` for `std::stacktrace_entry` allows users to obtain hashes of values of type `std::stacktrace_entry`. `operator()` of this specialization is noexcept. ### Example ### See also | | | | --- | --- | | [hash](../hash "cpp/utility/hash") (C++11) | hash function object (class template) | | [std::hash<std::basic\_stacktrace>](../basic_stacktrace/hash "cpp/utility/basic stacktrace/hash") (C++23) | hash support for `std::basic_stacktrace` (class template specialization) | cpp std::stacktrace_entry::source_file std::stacktrace\_entry::source\_file ==================================== | | | | | --- | --- | --- | | ``` std::string source_file() const; ``` | | (since C++23) | Returns the presumed or actual name of the source file that lexically contains the expression or statement whose evaluation is represented by `*this`, or an empty string on failure other than allocation failure, e.g. when `*this` is empty. Either `source_file` returns the presumed source file name and [`source_line`](source_line "cpp/utility/stacktrace entry/source line") returns the presumed line number, or `source_file` returns the actual source file name and [`source_line`](source_line "cpp/utility/stacktrace entry/source line") returns the actual line number. ### Parameters (none). ### Return value The name of the source file specified above on success, an empty string on failure other than allocation failure. ### Exceptions Throws `[std::bad\_alloc](../../memory/new/bad_alloc "cpp/memory/new/bad alloc")` if memory for the internal data structures or the resulting string cannot be allocated. ### Notes The presumed name of the source file is what the predefined macro [`__FILE__`](../../preprocessor/replace "cpp/preprocessor/replace") expands to, and can be changed by the [`#line`](../../preprocessor/line "cpp/preprocessor/line") directive. Custom allocators support for this function is not provided, because the implementations usually require platform specific allocations, system calls and a lot of CPU intensive work, while a custom allocator does not provide benefits for this function as the platform specific operations take an order of magnitude more time than the allocation. ### Example ### See also | | | | --- | --- | | [file\_name](../source_location/file_name "cpp/utility/source location/file name") | return the file name represented by this object (public member function of `std::source_location`) | cpp std::stacktrace_entry::operator bool std::stacktrace\_entry::operator bool ===================================== | | | | | --- | --- | --- | | ``` constexpr explicit operator bool() const noexcept; ``` | | (since C++23) | Checks whether the `stacktrace_entry` is non-empty, i.e. it represents an evaluation in a stacktrace. ### Parameters (none). ### Return value `true` if the `stacktrace_entry` is non-empty, `false` otherwise. ### Notes A non-empty `stacktrace_entry` can be obtained from a `std::basic_stacktrace` created by `std::basic_stacktrace::current` or a copy of such `std::basic_stacktrace`. An empty `stacktrace_entry` can be created by the [default constructor](stacktrace_entry "cpp/utility/stacktrace entry/stacktrace entry"). ### Example cpp std::stacktrace_entry::description std::stacktrace\_entry::description =================================== | | | | | --- | --- | --- | | ``` std::string description() const; ``` | | (since C++23) | Returns a description of the evaluation represented by `*this` on success, or an empty string on failure other than allocation failure, e.g. when `*this` is empty. ### Parameters (none). ### Return value A description of the represented evaluation on success, an empty string on failure other than allocation failure. ### Exceptions Throws `[std::bad\_alloc](../../memory/new/bad_alloc "cpp/memory/new/bad alloc")` if memory for the internal data structures or the resulting string cannot be allocated. ### Notes Custom allocators support for this function is not provided, because the implementations usually require platform specific allocations, system calls and a lot of CPU intensive work, while a custom allocator does not provide benefits for this function as the platform specific operations take an order of magnitude more time than the allocation. ### Example cpp std::stacktrace_entry::operator= std::stacktrace\_entry::operator= ================================= | | | | | --- | --- | --- | | ``` constexpr stacktrace_entry& operator=( const stacktrace_entry& other ) noexcept; ``` | | (since C++23) | Copy assignment operator. Replaces the contents of `*this` with those of `other`. ### Parameters | | | | | --- | --- | --- | | other | - | another `stacktrace_entry` to assign from | ### Return value `*this`.
programming_docs
cpp std::stacktrace_entry::native_handle std::stacktrace\_entry::native\_handle ====================================== | | | | | --- | --- | --- | | ``` constexpr native_handle_type native_handle() const noexcept; ``` | | (since C++23) | Returns the implementation-defined underlying native handle. Successive invocations of this function for an unchanged `stacktrace_entry` object return identical values. The semantics of this function is implementation-defined. ### Parameters (none). ### Return value Underlying native handle. ### Example cpp operator==, operator<=>(std::stacktrace_entry) operator==, operator<=>(std::stacktrace\_entry) =============================================== | | | | | --- | --- | --- | | ``` friend constexpr bool operator==( const stacktrace_entry& lhs, const stacktrace_entry& rhs ) noexcept; ``` | (1) | (since C++23) | | ``` friend constexpr std::strong_ordering operator<=>( const stacktrace_entry& lhs, const stacktrace_entry& rhs ) noexcept; ``` | (2) | (since C++23) | 1) Compares `lhs` and `rhs` for equality. Two `stacktrace_entry` values are equal if and only if they represent the same stacktrace entry, or both of them are empty. 2) Gets the relative order between `lhs` and `rhs` in the unspecified strict total order over all `stacktrace_entry` values which is consistent with the equality relation established by `operator==`. These functions are not visible to ordinary [unqualified](../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../language/adl "cpp/language/adl") when `std::stacktrace_entry` is an associated class of the arguments. The `<`, `<=`, `>`, `>=`, and `!=` operators are [synthesized](../../language/operators#Relational_operators "cpp/language/operators") from `operator<=>` and `operator==` respectively. ### Parameters | | | | | --- | --- | --- | | lhs, rhs | - | `stacktrace_entry` values to compare | ### Return value 1) `true` if two `lhs` and `rhs` compare equal, `false` otherwise. 2) `std::strong_ordering::equal` if `lhs` and `rhs` compare equal. Otherwise, `std::strong_ordering::less` if `lhs` is ordered before `rhs` in the strict total order. Otherwise, `std::strong_ordering::greater` (in which case `rhs` is ordered before `lhs` in the strict total order). ### Example cpp std::hash::hash std::hash::hash =============== The `[std::hash](../hash "cpp/utility/hash")` class should be [DefaultConstructible](../../named_req/defaultconstructible "cpp/named req/DefaultConstructible"), [CopyConstructible](../../named_req/copyconstructible "cpp/named req/CopyConstructible"), and [Destructible](../../named_req/destructible "cpp/named req/Destructible"). cpp std::hash<Key>::operator() std::hash<Key>::operator() ========================== Specializations of `[std::hash](../hash "cpp/utility/hash")` should define an `operator()` that: * Takes a single argument `key` of type `Key`. * Returns a value of type `[std::size\_t](http://en.cppreference.com/w/cpp/types/size_t)` that represents the hash value of `key`. * For two parameters `k1` and `k2` that are equal, `[std::hash](http://en.cppreference.com/w/cpp/utility/hash)<Key>()(k1) == [std::hash](http://en.cppreference.com/w/cpp/utility/hash)<Key>()(k2)`. * For two different parameters `k1` and `k2` that are not equal, the probability that `[std::hash](http://en.cppreference.com/w/cpp/utility/hash)<Key>()(k1) == [std::hash](http://en.cppreference.com/w/cpp/utility/hash)<Key>()(k2)` should be very small, approaching `1.0/[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<size_t>::max()`. ### Parameters | | | | | --- | --- | --- | | key | - | the object to be hashed | ### Return value a `[std::size\_t](http://en.cppreference.com/w/cpp/types/size_t)` representing the hash value. ### Exceptions Hash functions should not throw exceptions. ### Example The following code shows how to specialize the `[std::hash](../hash "cpp/utility/hash")` template for a custom class. ``` #include <functional> #include <iostream> #include <string> struct Employee { std::string name; unsigned int ID; }; namespace std { template <> class hash<Employee> { public: size_t operator()(const Employee &employee) const { // computes the hash of an employee using a variant // of the Fowler-Noll-Vo hash function size_t result = 2166136261; for (size_t i = 0, ie = employee.name.size(); i != ie; ++i) { result = (result * 16777619) ^ employee.name[i]; } return result ^ (employee.ID << 1); } }; } int main() { Employee employee; employee.name = "Zaphod Beeblebrox"; employee.ID = 42; std::hash<Employee> hash_fn; std::cout << hash_fn(employee) << '\n'; } ``` Output: ``` 177237019 ``` cpp va_copy va\_copy ======== | Defined in header `[<cstdarg>](../../header/cstdarg "cpp/header/cstdarg")` | | | | --- | --- | --- | | ``` void va_copy( std::va_list dest, std::va_list src ); ``` | | (since C++11) | The `va_copy` macro copies `src` to `dest`. `[va\_end](va_end "cpp/utility/variadic/va end")` should be called on `dest` before the function returns or any subsequent re-initialization of `dest` (via calls to `[va\_start](va_start "cpp/utility/variadic/va start")` or `va_copy`). ### Parameters | | | | | --- | --- | --- | | dest | - | an instance of the `[va\_list](va_list "cpp/utility/variadic/va list")` type to initialize | | src | - | the source `[va\_list](va_list "cpp/utility/variadic/va list")` that will be used to initialize `dest` | ### Expanded value (none). ### Example ``` #include <iostream> #include <cstdarg> #include <cmath> double sample_stddev(int count, ...) { double sum = 0; std::va_list args1; va_start(args1, count); std::va_list args2; va_copy(args2, args1); for (int i = 0; i < count; ++i) { double num = va_arg(args1, double); sum += num; } va_end(args1); double mean = sum / count; double sum_sq_diff = 0; for (int i = 0; i < count; ++i) { double num = va_arg(args2, double); sum_sq_diff += (num-mean) * (num-mean); } va_end(args2); return std::sqrt(sum_sq_diff / count); } int main() { std::cout << sample_stddev(4, 25.0, 27.3, 26.9, 25.7) << '\n'; } ``` Output: ``` 0.920258 ``` ### See also | | | | --- | --- | | [va\_start](va_start "cpp/utility/variadic/va start") | enables access to variadic function arguments (function macro) | | [va\_arg](va_arg "cpp/utility/variadic/va arg") | accesses the next variadic function argument (function macro) | | [va\_end](va_end "cpp/utility/variadic/va end") | ends traversal of the variadic function arguments (function macro) | | [C documentation](https://en.cppreference.com/w/c/variadic/va_copy "c/variadic/va copy") for `va_copy` | cpp va_end va\_end ======= | Defined in header `[<cstdarg>](../../header/cstdarg "cpp/header/cstdarg")` | | | | --- | --- | --- | | ``` void va_end( std::va_list ap ); ``` | | | The `va_end` macro performs cleanup for an `ap` object initialized by a call to `[va\_start](va_start "cpp/utility/variadic/va start")` or `[va\_copy](va_copy "cpp/utility/variadic/va copy")`. `va_end` may modify `ap` so that it is no longer usable. If there is no corresponding call to `[va\_start](va_start "cpp/utility/variadic/va start")` or `[va\_copy](va_copy "cpp/utility/variadic/va copy")`, or if `va_end` is not called before a function that calls `[va\_start](va_start "cpp/utility/variadic/va start")` or `[va\_copy](va_copy "cpp/utility/variadic/va copy")` returns, the behavior is undefined. ### Parameters | | | | | --- | --- | --- | | ap | - | an instance of the `[va\_list](va_list "cpp/utility/variadic/va list")` type to clean up | ### Expanded value (none). ### See also | | | | --- | --- | | [va\_start](va_start "cpp/utility/variadic/va start") | enables access to variadic function arguments (function macro) | | [va\_copy](va_copy "cpp/utility/variadic/va copy") (C++11) | makes a copy of the variadic function arguments (function macro) | | [va\_arg](va_arg "cpp/utility/variadic/va arg") | accesses the next variadic function argument (function macro) | | [C documentation](https://en.cppreference.com/w/c/variadic/va_end "c/variadic/va end") for `va_end` | cpp va_arg va\_arg ======= | Defined in header `[<cstdarg>](../../header/cstdarg "cpp/header/cstdarg")` | | | | --- | --- | --- | | ``` T va_arg( std::va_list ap, T ); ``` | | | The `va_arg` macro expands to an expression of type `T` that corresponds to the next parameter from the `[va\_list](va_list "cpp/utility/variadic/va list")` `ap`. Prior to calling `va_arg`, `ap` must be initialized by a call to either `[va\_start](va_start "cpp/utility/variadic/va start")` or `[va\_copy](va_copy "cpp/utility/variadic/va copy")`, with no intervening call to `[va\_end](va_end "cpp/utility/variadic/va end")`. Each invocation of the `va_arg` macro modifies `ap` to point to the next variable argument. If the type of the next argument in `ap` (after promotions) is not compatible with `T`, the behavior is undefined, unless: * one type is a signed integer type, the other type is the corresponding unsigned integer type, and the value is representable in both types; or * one type is pointer to `void` and the other is a pointer to a character type (`char`, `signed char`, or `unsigned char`). If `va_arg` is called when there are no more arguments in `ap`, the behavior is undefined. ### Parameters | | | | | --- | --- | --- | | ap | - | an instance of the `[va\_list](va_list "cpp/utility/variadic/va list")` type | | T | - | the type of the next parameter in `ap` | ### Expanded value the next variable parameter in `ap`. ### Example ``` #include <iostream> #include <cstdarg> #include <cmath> double stddev(int count, ...) { double sum = 0; double sum_sq = 0; std::va_list args; va_start(args, count); for (int i = 0; i < count; ++i) { double num = va_arg(args, double); sum += num; sum_sq += num*num; } va_end(args); return std::sqrt(sum_sq/count - (sum/count)*(sum/count)); } int main() { std::cout << stddev(4, 25.0, 27.3, 26.9, 25.7) << '\n'; } ``` Output: ``` 0.920258 ``` ### See also | | | | --- | --- | | [va\_start](va_start "cpp/utility/variadic/va start") | enables access to variadic function arguments (function macro) | | [va\_copy](va_copy "cpp/utility/variadic/va copy") (C++11) | makes a copy of the variadic function arguments (function macro) | | [va\_end](va_end "cpp/utility/variadic/va end") | ends traversal of the variadic function arguments (function macro) | | [C documentation](https://en.cppreference.com/w/c/variadic/va_arg "c/variadic/va arg") for `va_arg` | cpp std::va_list std::va\_list ============= | Defined in header `[<cstdarg>](../../header/cstdarg "cpp/header/cstdarg")` | | | | --- | --- | --- | | ``` typedef /* unspecified */ va_list; ``` | | | `va_list` is a complete object type suitable for holding the information needed by the macros `[va\_start](va_start "cpp/utility/variadic/va start")`, `[va\_copy](va_copy "cpp/utility/variadic/va copy")`, `[va\_arg](va_arg "cpp/utility/variadic/va arg")`, and `[va\_end](va_end "cpp/utility/variadic/va end")`. If a `va_list` instance is created, passed to another function, and used via `[va\_arg](va_arg "cpp/utility/variadic/va arg")` in that function, then any subsequent use in the calling function should be preceded by a call to `[va\_end](va_end "cpp/utility/variadic/va end")`. It is legal to pass a pointer to a `va_list` object to another function and then use that object after the function returns. ### See also | | | | --- | --- | | [va\_start](va_start "cpp/utility/variadic/va start") | enables access to variadic function arguments (function macro) | | [va\_copy](va_copy "cpp/utility/variadic/va copy") (C++11) | makes a copy of the variadic function arguments (function macro) | | [va\_arg](va_arg "cpp/utility/variadic/va arg") | accesses the next variadic function argument (function macro) | | [va\_end](va_end "cpp/utility/variadic/va end") | ends traversal of the variadic function arguments (function macro) | | [C documentation](https://en.cppreference.com/w/c/variadic/va_list "c/variadic/va list") for `va_list` | cpp va_start va\_start ========= | Defined in header `[<cstdarg>](../../header/cstdarg "cpp/header/cstdarg")` | | | | --- | --- | --- | | ``` void va_start( std::va_list ap, parm_n ); ``` | | | The `va_start` macro enables access to the variable arguments following the named argument `parm_n`. `va_start` should be invoked with an instance to a valid `[va\_list](va_list "cpp/utility/variadic/va list")` object `ap` before any calls to `[va\_arg](va_arg "cpp/utility/variadic/va arg")`. | | | | --- | --- | | If the `parm_n` is a [pack expansion](../../language/parameter_pack#Pack_expansion "cpp/language/parameter pack") or an entity resulting from a [lambda capture](../../language/lambda#Lambda_capture "cpp/language/lambda"), the program is ill-formed, no diagnostic required. | (since C++11) | If `parm_n` is declared with reference type or with a type not compatible with the type that results from [default argument promotions](../../language/variadic_arguments#Default_conversions "cpp/language/variadic arguments"), the behavior is undefined. ### Parameters | | | | | --- | --- | --- | | ap | - | an instance of the `[va\_list](va_list "cpp/utility/variadic/va list")` type | | parm\_n | - | the named parameter preceding the first variable parameter | ### Expanded value (none). ### Notes `va_start` is required to support `parm_n` with overloaded `operator&`. ### Example ``` #include <iostream> #include <cstdarg> int add_nums(int count, ...) { int result = 0; std::va_list args; va_start(args, count); for (int i = 0; i < count; ++i) { result += va_arg(args, int); } va_end(args); return result; } int main() { std::cout << add_nums(4, 25, 25, 50, 50) << '\n'; } ``` Output: ``` 150 ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 273](https://cplusplus.github.io/CWG/issues/273.html) | C++98 | `va_start` may not work if unary `operator&` is overloaded | required to work correctly even if `operator&` is overloaded | ### See also | | | | --- | --- | | [va\_arg](va_arg "cpp/utility/variadic/va arg") | accesses the next variadic function argument (function macro) | | [va\_end](va_end "cpp/utility/variadic/va end") | ends traversal of the variadic function arguments (function macro) | | [C documentation](https://en.cppreference.com/w/c/variadic/va_start "c/variadic/va start") for `va_start` | cpp deduction guides for std::tuple deduction guides for `std::tuple` ================================= | Defined in header `[<tuple>](../../header/tuple "cpp/header/tuple")` | | | | --- | --- | --- | | ``` template<class... UTypes> tuple(UTypes...) -> tuple<UTypes...>; ``` | (1) | (since C++17) | | ``` template<class T1, class T2> tuple(std::pair<T1, T2>) -> tuple<T1, T2>; ``` | (2) | (since C++17) | | ``` template<class Alloc, class... UTypes> tuple(std::allocator_arg_t, Alloc, UTypes...) -> tuple<UTypes...>; ``` | (3) | (since C++17) | | ``` template<class Alloc, class T1, class T2> tuple(std::allocator_arg_t, Alloc, std::pair<T1, T2>) -> tuple<T1, T2>; ``` | (4) | (since C++17) | | ``` template<class Alloc, class... UTypes> tuple(std::allocator_arg_t, Alloc, tuple<UTypes...>) -> tuple<UTypes...>; ``` | (5) | (since C++17) | These [deduction guides](../../language/class_template_argument_deduction "cpp/language/class template argument deduction") are provided for `[std::tuple](../tuple "cpp/utility/tuple")` to account for the edge cases missed by the implicit deduction guides, in particular, non-copyable arguments and array to pointer conversion. ### Example ``` #include <tuple> int main() { int a[2], b[3], c[4]; std::tuple t1{a, b, c}; // explicit deduction guide is used in this case } ``` cpp std::tuple<Types...>::tuple std::tuple<Types...>::tuple =========================== | Defined in header `[<tuple>](../../header/tuple "cpp/header/tuple")` | | | | --- | --- | --- | | ``` constexpr tuple(); ``` | (1) | (since C++11) (conditionally explicit) | | ``` tuple( const Types&... args ); ``` | (2) | (since C++11) (constexpr since C++14)(conditionally explicit) | | ``` template< class... UTypes > tuple( UTypes&&... args ); ``` | (3) | (since C++11) (constexpr since C++14)(conditionally explicit) | | ``` template< class... UTypes > constexpr tuple( tuple<UTypes...>& other ); ``` | (4) | (since C++23) (conditionally explicit) | | ``` template< class... UTypes > tuple( const tuple<UTypes...>& other ); ``` | (5) | (since C++11) (constexpr since C++14)(conditionally explicit) | | ``` template< class... UTypes > tuple( tuple<UTypes...>&& other ); ``` | (6) | (since C++11) (constexpr since C++14)(conditionally explicit) | | ``` template< class... UTypes > constexpr tuple( const tuple<UTypes...>&& other ); ``` | (7) | (since C++23) (conditionally explicit) | | ``` template< class U1, class U2 > constexpr tuple( std::pair<U1, U2>& p ); ``` | (8) | (since C++23) (conditionally explicit) | | ``` template< class U1, class U2 > tuple( const std::pair<U1, U2>& p ); ``` | (9) | (since C++11) (constexpr since C++14)(conditionally explicit) | | ``` template< class U1, class U2 > tuple( std::pair<U1, U2>&& p ); ``` | (10) | (since C++11) (constexpr since C++14)(conditionally explicit) | | ``` template< class U1, class U2 > constexpr tuple( const std::pair<U1, U2>&& p ); ``` | (11) | (since C++23) (conditionally explicit) | | ``` tuple( const tuple& other ) = default; ``` | (12) | (since C++11) | | ``` tuple( tuple&& other ) = default; ``` | (13) | (since C++11) | | ``` template< class Alloc > tuple( std::allocator_arg_t, const Alloc& a ); ``` | (14) | (since C++11) (constexpr since C++20)(conditionally explicit) | | ``` template< class Alloc > tuple( std::allocator_arg_t, const Alloc& a, const Types&... args ); ``` | (15) | (since C++11) (constexpr since C++20)(conditionally explicit) | | ``` template< class Alloc, class... UTypes > tuple( std::allocator_arg_t, const Alloc& a, UTypes&&... args ); ``` | (16) | (since C++11) (constexpr since C++20)(conditionally explicit) | | ``` template< class Alloc, class... UTypes > constexpr tuple( std::allocator_arg_t, const Alloc& a, tuple<UTypes...>& other ); ``` | (17) | (since C++23) (conditionally explicit) | | ``` template< class Alloc, class... UTypes > tuple( std::allocator_arg_t, const Alloc& a, const tuple<UTypes...>& other ); ``` | (18) | (since C++11) (constexpr since C++20)(conditionally explicit) | | ``` template< class Alloc, class... UTypes > tuple( std::allocator_arg_t, const Alloc& a, tuple<UTypes...>&& other ); ``` | (19) | (since C++11) (constexpr since C++20)(conditionally explicit) | | ``` template< class Alloc, class... UTypes > constexpr tuple( std::allocator_arg_t, const Alloc& a, const tuple<UTypes...>&& other ); ``` | (20) | (since C++23) (conditionally explicit) | | ``` template< class Alloc, class U1, class U2 > constexpr tuple( std::allocator_arg_t, const Alloc& a, std::pair<U1, U2>& p ); ``` | (21) | (since C++23) (conditionally explicit) | | ``` template< class Alloc, class U1, class U2 > tuple( std::allocator_arg_t, const Alloc& a, const std::pair<U1, U2>& p ); ``` | (22) | (since C++11) (constexpr since C++20)(conditionally explicit) | | ``` template< class Alloc, class U1, class U2 > tuple( std::allocator_arg_t, const Alloc& a, std::pair<U1, U2>&& p ); ``` | (23) | (since C++11) (constexpr since C++20)(conditionally explicit) | | ``` template< class Alloc, class U1, class U2 > constexpr tuple( std::allocator_arg_t, const Alloc& a, const std::pair<U1, U2>&& p ); ``` | (24) | (since C++23) (conditionally explicit) | | ``` template< class Alloc > tuple( std::allocator_arg_t, const Alloc& a, const tuple& other ); ``` | (25) | (since C++11) (constexpr since C++20) | | ``` template< class Alloc > tuple( std::allocator_arg_t, const Alloc& a, tuple&& other ); ``` | (26) | (since C++11) (constexpr since C++20) | Constructs a new tuple. 1) Default constructor. [Value-initializes](../../language/value_initialization "cpp/language/value initialization") all elements, if any. The default constructor is trivial if `sizeof...(Types) == 0`. * This overload participates in overload resolution only if `[std::is\_default\_constructible](http://en.cppreference.com/w/cpp/types/is_default_constructible)<Ti>::value` is `true` for all `i` * The constructor is `explicit` if and only if `Ti` is not copy-list-initializable from `{}` for at least one `i`. 2) Direct constructor. Initializes each element of the tuple with the corresponding parameter. * This overload participates in overload resolution only if `sizeof...(Types) >= 1` and `[std::is\_copy\_constructible](http://en.cppreference.com/w/cpp/types/is_copy_constructible)<Ti>::value` is `true` for all `i`. * This constructor is `explicit` if and only if `[std::is\_convertible](http://en.cppreference.com/w/cpp/types/is_convertible)<const Ti&, Ti>::value` is `false` for at least one `i`. 3) Converting constructor. Initializes each element of the tuple with the corresponding value in `[std::forward](http://en.cppreference.com/w/cpp/utility/forward)<UTypes>(args)`. * This overload participates in overload resolution only if + `sizeof...(Types) == sizeof...(UTypes)`, and + `sizeof...(Types) >= 1`, and + `[std::is\_constructible](http://en.cppreference.com/w/cpp/types/is_constructible)<Ti, Ui>::value` is `true` for all `i`, and + let `D` be `[std::decay](http://en.cppreference.com/w/cpp/types/decay)<U0>::type` (until C++20)`[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<U0>` (since C++20), - if `sizeof...(Types) == 1`, then `D` is not `tuple`, otherwise, - if `sizeof...(Types) == 2` or `sizeof...(Types) == 3`, then either `D` is not `[std::allocator\_arg\_t](../../memory/allocator_arg_t "cpp/memory/allocator arg t")`, or `T0` is `[std::allocator\_arg\_t](../../memory/allocator_arg_t "cpp/memory/allocator arg t")`. * The constructor is `explicit` if and only if `[std::is\_convertible](http://en.cppreference.com/w/cpp/types/is_convertible)<Ui, Ti>::value` is `false` for at least one `i`. | | | | --- | --- | | * This constructor is defined as deleted if the initialization of any element that is a reference would [bind it to a temporary object](../../language/reference_initialization#Lifetime_of_a_temporary "cpp/language/reference initialization"). | (since C++23) | 4-7) Converting copy-constructor. Initializes each element of the tuple with the corresponding element of `other`. Formally, let `FWD(other)` be `[std::forward](http://en.cppreference.com/w/cpp/utility/forward)<decltype(other)>(other)`, for all `i` in `sizeof...(UTypes)`, initializes ith element of the tuple with `[std::get](http://en.cppreference.com/w/cpp/utility/variant/get)<i>(FWD(other))`. * This overload participates in overload resolution only if + `sizeof...(Types) == sizeof...(UTypes)` and + `[std::is\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_constructible)<Ti, decltype([std::get](http://en.cppreference.com/w/cpp/utility/variant/get)<i>(FWD(other)))>` is `true` for all `i` and + either - `sizeof...(Types) != 1` or - (when `Types...` expands to `T` and `UTypes...` expands to `U`) `[std::is\_convertible\_v](http://en.cppreference.com/w/cpp/types/is_convertible)<decltype(other), T>`, `[std::is\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_constructible)<T, decltype(other)>`, and `[std::is\_same\_v](http://en.cppreference.com/w/cpp/types/is_same)<T, U>` are all `false`. * These constructors are `explicit` if and only if `[std::is\_convertible\_v](http://en.cppreference.com/w/cpp/types/is_convertible)<decltype([std::get](http://en.cppreference.com/w/cpp/utility/variant/get)<i>(FWD(other))), Ti>` is `false` for at least one `i`. | | | | --- | --- | | * These constructors are defined as deleted if the initialization of any element that is a reference would bind it to a temporary object. | (since C++23) | 8-11) Pair copy constructor. Constructs a 2-element tuple with each element constructed from the corresponding element of `p`. Formally, let `FWD(p)` be `[std::forward](http://en.cppreference.com/w/cpp/utility/forward)<decltype(p)>(p)`, initializes the first element with `[std::get](http://en.cppreference.com/w/cpp/utility/variant/get)<0>(FWD(p))` and the second element with `[std::get](http://en.cppreference.com/w/cpp/utility/variant/get)<1>(FWD(p))`. * This overload participates in overload resolution only if `sizeof...(Types) == 2` and `[std::is\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_constructible)<T0, decltype([std::get](http://en.cppreference.com/w/cpp/utility/variant/get)<0>(FWD(p)))>` and `[std::is\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_constructible)<T1, decltype([std::get](http://en.cppreference.com/w/cpp/utility/variant/get)<1>(FWD(p)))>` are both `true` * The constructor is `explicit` if and only if `[std::is\_convertible\_v](http://en.cppreference.com/w/cpp/types/is_convertible)<decltype([std::get](http://en.cppreference.com/w/cpp/utility/variant/get)<0>(FWD(p))), T0>` or `[std::is\_convertible\_v](http://en.cppreference.com/w/cpp/types/is_convertible)<decltype([std::get](http://en.cppreference.com/w/cpp/utility/variant/get)<1>(FWD(p))), T1>` is `false`. | | | | --- | --- | | * These constructors are defined as deleted if the initialization of any element that is a reference would bind it to a temporary object. | (since C++23) | 12) Implicitly-defined copy constructor. Initializes each element of the tuple with the corresponding element of `other`. * This constructor is `constexpr` if every operation it performs is `constexpr`. For the empty tuple `[std::tuple](http://en.cppreference.com/w/cpp/utility/tuple)<>`, it is `constexpr`. * `[std::is\_copy\_constructible](http://en.cppreference.com/w/cpp/types/is_copy_constructible)<Ti>::value` must be `true` for all `i`, otherwise the behavior is undefined (until C++20)the program is ill-formed (since C++20). 13) Implicitly-defined move constructor. Initializes each ith element of the tuple with `[std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Ui>([std::get](http://en.cppreference.com/w/cpp/utility/variant/get)<i>(other))`. * This constructor is `constexpr` if every operation it performs is `constexpr`. For the empty tuple `[std::tuple](http://en.cppreference.com/w/cpp/utility/tuple)<>`, it is `constexpr`. * `[std::is\_move\_constructible](http://en.cppreference.com/w/cpp/types/is_move_constructible)<Ti>::value` must be `true` for all `i`, otherwise the behavior is undefined (until C++20)this overload does not participate in overload resolution (since C++20). 14-26) Identical to (1-13) except each element is created by [uses-allocator construction](../../memory/uses_allocator#Uses-allocator_construction "cpp/memory/uses allocator"), that is, the Allocator object `a` is passed as an additional argument to the constructor of each element for which `[std::uses\_allocator](http://en.cppreference.com/w/cpp/memory/uses_allocator)<Ui, Alloc>::value` is `true`. ### Parameters | | | | | --- | --- | --- | | args | - | values used to initialize each element of the tuple | | other | - | a tuple of values used to initialize each element of the tuple | | p | - | pair of values used to initialize both elements of this 2-tuple | | a | - | allocator to use in uses-allocator construction | ### Notes Conditionally-explicit constructors make it possible to construct a tuple in copy-initialization context using list-initialization syntax: ``` std::tuple<int, int> foo_tuple() { return {1, -1}; // Error before N4387 return std::make_tuple(1, -1); // Always works } ``` Note that if some element of the list is not implicitly convertible to the corresponding element of the target tuple, the constructors become explicit: ``` using namespace std::chrono; void launch_rocket_at(std::tuple<hours, minutes, seconds>); launch_rocket_at({hours(1), minutes(2), seconds(3)}); // OK launch_rocket_at({1, 2, 3}); // Error: int is not implicitly convertible to duration launch_rocket_at(std::tuple<hours, minutes, seconds>{1, 2, 3}); // OK ``` ### Example ``` #include <iomanip> #include <iostream> #include <memory> #include <string> #include <tuple> #include <type_traits> #include <vector> // helper function to print a vector to a stream template<class Os, class T> Os& operator<< (Os& os, std::vector<T> const& v) { os << '{'; for (auto i{v.size()}; const T& e : v) os << e << (--i ? "," : ""); return os << '}'; } template<class T> void print_single(T const& v) { if constexpr (std::is_same_v<T, std::decay_t<std::string>>) std::cout << std::quoted(v); else if constexpr (std::is_same_v<std::decay_t<T>, char>) std::cout << "'" << v << "'"; else std::cout << v; } // helper function to print a tuple of any size template<class Tuple, std::size_t N> struct TuplePrinter { static void print(const Tuple& t) { TuplePrinter<Tuple, N-1>::print(t); std::cout << ", "; print_single(std::get<N-1>(t)); } }; template<class Tuple> struct TuplePrinter<Tuple, 1>{ static void print(const Tuple& t) { print_single(std::get<0>(t)); } }; template<class... Args> void print(const std::tuple<Args...>& t) { std::cout << "("; TuplePrinter<decltype(t), sizeof...(Args)>::print(t); std::cout << ")\n"; } // end helper function int main() { std::tuple<int, std::string, double> t1; std::cout << "Value-initialized, t1: "; print(t1); std::tuple<int, std::string, double> t2{42, "Test", -3.14}; std::cout << "Initialized with values, t2: "; print(t2); std::tuple<char, std::string, int> t3{t2}; std::cout << "Implicitly converted, t3: "; print(t3); std::tuple<int, double> t4{std::make_pair(42, 3.14)}; std::cout << "Constructed from a pair, t4: "; print(t4); // given Allocator my_alloc with a single-argument constructor // my_alloc(int); use my_alloc(1) to allocate 5 ints in a vector using my_alloc = std::allocator<int>; std::vector<int, my_alloc> v { 5, 1, my_alloc{/*1*/} }; // use my_alloc(2) to allocate 5 ints in a vector in a tuple std::tuple<int, std::vector<int, my_alloc>, double> t5{ std::allocator_arg, my_alloc{/*2*/}, 42, v, -3.14}; std::cout << "Constructed with allocator, t5: "; print(t5); } ``` Possible output: ``` Value-initialized, t1: (0, "", 0) Initialized with values, t2: (42, "Test", -3.14) Implicitly converted, t3: ('*', "Test", -3) Constructed from a pair, t4: (42, 3.14) Constructed with allocator, t5: (42, {1,1,1,1,1}, -3.14) ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [N4387](https://wg21.link/N4387) | C++11 | some constructors were explicit, preventing useful behavior | most constructors made conditionally-explicit | | [LWG 2510](https://cplusplus.github.io/LWG/issue2510) | C++11 | default constructor was implicit | made conditionally-explicit | | [LWG 3121](https://cplusplus.github.io/LWG/issue3121) | C++11 | constructor of 1-tuple might recursively check the constraints;`allocator_arg_t` argument brought ambiguity | furtherly constrained the constructor | | [LWG 3158](https://cplusplus.github.io/LWG/issue3158) | C++11 | the uses-allocator constructor corresponding todefault constructor was implicit | made conditionally-explicit | | [LWG 3211](https://cplusplus.github.io/LWG/issue3211) | C++11 | whether the default constructor of`tuple<>` is trivial was unspecified | require to be trivial | ### See also | | | | --- | --- | | [operator=](operator= "cpp/utility/tuple/operator=") (C++11) | assigns the contents of one `tuple` to another (public member function) | | [make\_tuple](make_tuple "cpp/utility/tuple/make tuple") (C++11) | creates a `tuple` object of the type defined by the argument types (function template) | | [tie](tie "cpp/utility/tuple/tie") (C++11) | creates a `[tuple](../tuple "cpp/utility/tuple")` of lvalue references or unpacks a tuple into individual objects (function template) | | [forward\_as\_tuple](forward_as_tuple "cpp/utility/tuple/forward as tuple") (C++11) | creates a `tuple` of [forwarding references](../../language/reference#Forwarding_references "cpp/language/reference") (function template) | | [(constructor)](../pair/pair "cpp/utility/pair/pair") | constructs new pair (public member function of `std::pair<T1,T2>`) |
programming_docs
cpp std::basic_common_reference<tuple-like> std::basic\_common\_reference<*tuple-like*> =========================================== | Defined in header `[<tuple>](../../header/tuple "cpp/header/tuple")` | | | | --- | --- | --- | | ``` template< /*tuple-like*/ TTuple, /*tuple-like*/ UTuple, template<class> class TQual, template<class> class UQual > requires /* see below */ struct basic_common_reference<TTuple, UTuple, TQual, UQual>; ``` | | (since C++23) | The common reference type of two tuple-like types is a `tuple` consists of the common reference types of all corresponding element type pairs of both types, where the cv and reference qualifiers on the tuple-like types are applied to their element types. The common type is defined only if. * both `TTuple` and `UTuple` are cv-unqualified tuple-like types, and * either `TTuple` or `UTuple` is a `[std::tuple](../tuple "cpp/utility/tuple")` specialization, and * both `TTuple` and `UTuple` have the same number of elements (as determined by `[std::tuple\_size\_v](tuple_size "cpp/utility/tuple/tuple size")`), and * all corresponding element type pairs of `TTuple` and `UTuple` have common reference types. ### Member types | Member type | Definition | | --- | --- | | `type` | `[std::tuple](http://en.cppreference.com/w/cpp/utility/tuple)<[std::common\_reference\_t](http://en.cppreference.com/w/cpp/types/common_reference)<TQual<TTypes>..., UQual<UTypes>>...>` | In the table above, `TTypes...` and `UTypes...` denotes the sequence of element types of `TTuple` and `UTuple` respectively, where each elements type of `TupleLike` at given index `I` is `[std::tuple\_element\_t](http://en.cppreference.com/w/cpp/utility/tuple/tuple_element)<I, TupleLike>`. ### Example ### See also | | | | --- | --- | | [common\_referencebasic\_common\_reference](../../types/common_reference "cpp/types/common reference") (C++20) | determines the common reference type of a group of types (class template) | | [std::basic\_common\_reference<std::pair>](../pair/basic_common_reference "cpp/utility/pair/basic common reference") (C++23) | determines the common reference type of two `pair`s (class template specialization) | cpp std::tie std::tie ======== | Defined in header `[<tuple>](../../header/tuple "cpp/header/tuple")` | | | | --- | --- | --- | | ``` template< class... Types > std::tuple<Types&...> tie( Types&... args ) noexcept; ``` | | (since C++11) (until C++14) | | ``` template< class... Types > constexpr std::tuple<Types&...> tie( Types&... args ) noexcept; ``` | | (since C++14) | Creates a tuple of lvalue references to its arguments or instances of `[std::ignore](ignore "cpp/utility/tuple/ignore")`. ### Parameters | | | | | --- | --- | --- | | args | - | zero or more lvalue arguments to construct the tuple from. | ### Return value A `[std::tuple](../tuple "cpp/utility/tuple")` object containing lvalue references. ### Possible implementation | | | --- | | ``` template <typename... Args> constexpr // since C++14 std::tuple<Args&...> tie(Args&... args) noexcept { return {args...}; } ``` | ### Notes `std::tie` may be used to unpack a `[std::pair](../pair "cpp/utility/pair")` because `[std::tuple](../tuple "cpp/utility/tuple")` has a [converting assignment](operator= "cpp/utility/tuple/operator=") from pairs: ``` bool result; std::tie(std::ignore, result) = set.insert(value); ``` ### Example `std::tie` can be used to introduce lexicographical comparison to a struct or to unpack a tuple: ``` #include <iostream> #include <string> #include <set> #include <tuple> struct S { int n; std::string s; float d; bool operator<(const S& rhs) const { // compares n to rhs.n, // then s to rhs.s, // then d to rhs.d return std::tie(n, s, d) < std::tie(rhs.n, rhs.s, rhs.d); } }; int main() { std::set<S> set_of_s; // S is LessThanComparable S value{42, "Test", 3.14}; std::set<S>::iterator iter; bool inserted; // unpacks the return value of insert into iter and inserted std::tie(iter, inserted) = set_of_s.insert(value); if (inserted) std::cout << "Value was inserted successfully\n"; } ``` Output: ``` Value was inserted successfully ``` ### See also | | | | --- | --- | | [Structured binding](../../language/structured_binding "cpp/language/structured binding") (C++17) | binds the specified names to sub-objects or tuple elements of the initializer | | [make\_tuple](make_tuple "cpp/utility/tuple/make tuple") (C++11) | creates a `tuple` object of the type defined by the argument types (function template) | | [forward\_as\_tuple](forward_as_tuple "cpp/utility/tuple/forward as tuple") (C++11) | creates a `tuple` of [forwarding references](../../language/reference#Forwarding_references "cpp/language/reference") (function template) | | [tuple\_cat](tuple_cat "cpp/utility/tuple/tuple cat") (C++11) | creates a `tuple` by concatenating any number of tuples (function template) | | [ignore](ignore "cpp/utility/tuple/ignore") (C++11) | placeholder to skip an element when unpacking a `tuple` using **`tie`** (constant) | cpp std::forward_as_tuple std::forward\_as\_tuple ======================= | Defined in header `[<tuple>](../../header/tuple "cpp/header/tuple")` | | | | --- | --- | --- | | ``` template< class... Types > tuple<Types&&...> forward_as_tuple( Types&&... args ) noexcept; ``` | | (since C++11) (constexpr since C++14) | Constructs a tuple of references to the arguments in `args` suitable for forwarding as an argument to a function. The tuple has rvalue reference data members when rvalues are used as arguments, and otherwise has lvalue reference data members. ### Parameters | | | | | --- | --- | --- | | args | - | zero or more arguments to construct the tuple from | ### Return value A `[std::tuple](../tuple "cpp/utility/tuple")` object created as if by `[std::tuple](http://en.cppreference.com/w/cpp/utility/tuple)<Types&&...>([std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Types>(args)...)`. ### Notes If the arguments are temporaries, `forward_as_tuple` does not extend their lifetime; they have to be used before the end of the full expression. ### Example ``` #include <iostream> #include <map> #include <tuple> #include <string> int main() { std::map<int, std::string> m; m.emplace(std::piecewise_construct, std::forward_as_tuple(10), std::forward_as_tuple(20, 'a')); std::cout << "m[10] = " << m[10] << '\n'; // The following is an error: it produces a // std::tuple<int&&, char&&> holding two dangling references. // // auto t = std::forward_as_tuple(20, 'a'); // m.emplace(std::piecewise_construct, std::forward_as_tuple(10), t); } ``` Output: ``` m[10] = aaaaaaaaaaaaaaaaaaaa ``` ### See also | | | | --- | --- | | [make\_tuple](make_tuple "cpp/utility/tuple/make tuple") (C++11) | creates a `tuple` object of the type defined by the argument types (function template) | | [tie](tie "cpp/utility/tuple/tie") (C++11) | creates a `[tuple](../tuple "cpp/utility/tuple")` of lvalue references or unpacks a tuple into individual objects (function template) | | [tuple\_cat](tuple_cat "cpp/utility/tuple/tuple cat") (C++11) | creates a `tuple` by concatenating any number of tuples (function template) | | [apply](../apply "cpp/utility/apply") (C++17) | calls a function with a tuple of arguments (function template) | cpp std::tuple_cat std::tuple\_cat =============== | Defined in header `[<tuple>](../../header/tuple "cpp/header/tuple")` | | | | --- | --- | --- | | ``` template< class... Tuples > std::tuple<CTypes...> tuple_cat(Tuples&&... args); ``` | | (since C++11) (constexpr since C++14) | Constructs a tuple that is a concatenation of all tuples in `args`. The behavior is undefined if any type in `[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<Tuples>...` is not a specialization of `[std::tuple](../tuple "cpp/utility/tuple")`. However, an implementation may choose to support types (such as `[std::array](../../container/array "cpp/container/array")` and `[std::pair](../pair "cpp/utility/pair")`) that follow the tuple-like protocol. ### Parameters | | | | | --- | --- | --- | | args | - | zero or more tuples to concatenate | ### Return value A `[std::tuple](../tuple "cpp/utility/tuple")` object composed of all elements of all argument tuples constructed from `[std::get](http://en.cppreference.com/w/cpp/utility/variant/get)<j>([std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Ti>(arg))` for each individual element. ### Example ``` #include <iostream> #include <tuple> #include <string> // helper function to print a tuple of any size template<class Tuple, std::size_t N> struct TuplePrinter { static void print(const Tuple& t) { TuplePrinter<Tuple, N-1>::print(t); std::cout << ", " << std::get<N-1>(t); } }; template<class Tuple> struct TuplePrinter<Tuple, 1> { static void print(const Tuple& t) { std::cout << std::get<0>(t); } }; template<typename... Args, std::enable_if_t<sizeof...(Args) == 0, int> = 0> void print(const std::tuple<Args...>& t) { std::cout << "()\n"; } template<typename... Args, std::enable_if_t<sizeof...(Args) != 0, int> = 0> void print(const std::tuple<Args...>& t) { std::cout << "("; TuplePrinter<decltype(t), sizeof...(Args)>::print(t); std::cout << ")\n"; } // end helper function int main() { std::tuple<int, std::string, float> t1(10, "Test", 3.14); int n = 7; auto t2 = std::tuple_cat(t1, std::make_tuple("Foo", "bar"), t1, std::tie(n)); n = 42; print(t2); } ``` Output: ``` (10, Test, 3.14, Foo, bar, 10, Test, 3.14, 42) ``` ### See also | | | | --- | --- | | [make\_tuple](make_tuple "cpp/utility/tuple/make tuple") (C++11) | creates a `tuple` object of the type defined by the argument types (function template) | | [tie](tie "cpp/utility/tuple/tie") (C++11) | creates a `[tuple](../tuple "cpp/utility/tuple")` of lvalue references or unpacks a tuple into individual objects (function template) | | [forward\_as\_tuple](forward_as_tuple "cpp/utility/tuple/forward as tuple") (C++11) | creates a `tuple` of [forwarding references](../../language/reference#Forwarding_references "cpp/language/reference") (function template) | cpp std::tuple<Types...>::swap std::tuple<Types...>::swap ========================== | Defined in header `[<tuple>](../../header/tuple "cpp/header/tuple")` | | | | --- | --- | --- | | | (1) | | | ``` void swap( tuple& other ) noexcept(/* see below */); ``` | (since C++11) (until C++20) | | ``` constexpr void swap( tuple& other ) noexcept(/* see below */); ``` | (since C++20) | | ``` constexpr void swap( const tuple& other ) noexcept(/* see below */) const; ``` | (2) | (since C++23) | Calls `swap` (which might be `[std::swap](../../algorithm/swap "cpp/algorithm/swap")`, or might be found via ADL) for each element in `*this` and its corresponding element in `other`. | | | | --- | --- | | If any selected `swap` function call is ill-formed, or does not swap the corresponding elements of both tuples, the behavior is undefined. | (until C++23) | | If any selected `swap` function call does not swap the corresponding elements of both tuples, the behavior is undefined. 1) The program is ill-formed if `([std::is\_swappable\_v](http://en.cppreference.com/w/cpp/types/is_swappable)<Types> && ...)` is not `true`. 2) The program is ill-formed if `([std::is\_swappable\_v](http://en.cppreference.com/w/cpp/types/is_swappable)<const Types> && ...)` is not `true`. | (since C++23) | ### Parameters | | | | | --- | --- | --- | | other | - | tuple of values to swap | ### Return value (none). ### Exceptions | | | | --- | --- | | [`noexcept`](../../language/noexcept_spec "cpp/language/noexcept spec") specification: `noexcept( noexcept(swap([std::declval](http://en.cppreference.com/w/cpp/utility/declval)<T0&>>(), [std::declval](http://en.cppreference.com/w/cpp/utility/declval)<T0&>())) && noexcept(swap([std::declval](http://en.cppreference.com/w/cpp/utility/declval)<T1&>>(), [std::declval](http://en.cppreference.com/w/cpp/utility/declval)<T1&>())) && noexcept(swap([std::declval](http://en.cppreference.com/w/cpp/utility/declval)<T2&>>(), [std::declval](http://en.cppreference.com/w/cpp/utility/declval)<T2&>())) && ... )` In the expression above, the identifier `swap` is looked up in the same manner as the one used by the C++17 `[std::is\_nothrow\_swappable](../../types/is_swappable "cpp/types/is swappable")` trait. | (until C++17) | | 1) [`noexcept`](../../language/noexcept_spec "cpp/language/noexcept spec") specification: `noexcept(([std::is\_nothrow\_swappable\_v](http://en.cppreference.com/w/cpp/types/is_swappable)<Types> && ...))` 2) [`noexcept`](../../language/noexcept_spec "cpp/language/noexcept spec") specification: `noexcept(([std::is\_nothrow\_swappable\_v](http://en.cppreference.com/w/cpp/types/is_swappable)<const Types> && ...))` | (since C++17) | ### Example ``` #include <iostream> #include <string> #include <tuple> int main() { std::tuple<int, std::string, float> p1{42, "ABCD", 2.71}, p2; p2 = std::make_tuple(10, "1234", 3.14); auto print_p1_p2 = [&](auto rem) { std::cout << rem << "p1 = {" << std::get<0>(p1) << ", " << std::get<1>(p1) << ", " << std::get<2>(p1) << "}, " << "p2 = {" << std::get<0>(p2) << ", " << std::get<1>(p2) << ", " << std::get<2>(p2) << "}\n"; }; print_p1_p2("Before p1.swap(p2): "); p1.swap(p2); print_p1_p2("After p1.swap(p2): "); swap(p1, p2); print_p1_p2("After swap(p1, p2): "); } ``` Output: ``` Before p1.swap(p2): p1 = {42, ABCD, 2.71}, p2 = {10, 1234, 3.14} After p1.swap(p2): p1 = {10, 1234, 3.14}, p2 = {42, ABCD, 2.71} After swap(p1, p2): p1 = {42, ABCD, 2.71}, p2 = {10, 1234, 3.14} ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 2456](https://cplusplus.github.io/LWG/issue2456) | C++11 | the `noexcept` specification is ill-formed | made to work | ### See also | | | | --- | --- | | [std::swap(std::tuple)](swap2 "cpp/utility/tuple/swap2") (C++11) | specializes the `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | | [swap](../pair/swap "cpp/utility/pair/swap") (C++11) | swaps the contents (public member function of `std::pair<T1,T2>`) | cpp std::ignore std::ignore =========== | Defined in header `[<tuple>](../../header/tuple "cpp/header/tuple")` | | | | --- | --- | --- | | ``` const /*unspecified*/ ignore; ``` | | (since C++11) (until C++17) | | ``` inline constexpr /*unspecified*/ ignore; ``` | | (since C++17) | An object of unspecified type such that any value can be assigned to it with no effect. Intended for use with `[std::tie](tie "cpp/utility/tuple/tie")` when unpacking a `[std::tuple](../tuple "cpp/utility/tuple")`, as a placeholder for the arguments that are not used. While the behavior of `std::ignore` outside of `std::tie` is not formally specified, some code guides recommend using `std::ignore` to avoid warnings from unused return values of `[[[nodiscard](../../language/attributes/nodiscard "cpp/language/attributes/nodiscard")]]` functions. ### Possible implementation | | | --- | | ``` namespace detail { struct ignore_t { template <typename T> constexpr // required since C++14 void operator=(T&&) const noexcept {} }; } inline constexpr detail::ignore_t ignore; // 'const' only until C++17 ``` | ### Example 1. Demonstrates the use of `std::ignore` together with a `[[[nodiscard](../../language/attributes/nodiscard "cpp/language/attributes/nodiscard")]]` function. 2. Unpacks a `[std::pair](http://en.cppreference.com/w/cpp/utility/pair)<iterator, bool>` returned by [`set.insert()`](../../container/set/insert "cpp/container/set/insert"), but only saves the boolean. ``` #include <iostream> #include <string> #include <set> #include <tuple> [[nodiscard]] int dontIgnoreMe() { return 42; } int main() { std::ignore = dontIgnoreMe(); std::set<std::string> set_of_str; bool inserted = false; std::tie(std::ignore, inserted) = set_of_str.insert("Test"); if (inserted) { std::cout << "Value was inserted successfully\n"; } } ``` Output: ``` Value was inserted successfully ``` ### See also | | | | --- | --- | | [tie](tie "cpp/utility/tuple/tie") (C++11) | creates a `[tuple](../tuple "cpp/utility/tuple")` of lvalue references or unpacks a tuple into individual objects (function template) | cpp std::swap(std::tuple) std::swap(std::tuple) ===================== | Defined in header `[<tuple>](../../header/tuple "cpp/header/tuple")` | | | | --- | --- | --- | | | (1) | | | ``` template< class... Types > void swap( std::tuple<Types...>& lhs, std::tuple<Types...>& rhs ) noexcept(/* see below */); ``` | (since C++11) (until C++20) | | ``` template< class... Types > constexpr void swap( std::tuple<Types...>& lhs, std::tuple<Types...>& rhs ) noexcept(/* see below */); ``` | (since C++20) | | ``` template< class... Types > constexpr void swap( const std::tuple<Types...>& lhs, const std::tuple<Types...>& rhs ) noexcept(/* see below */); ``` | (2) | (since C++23) | Swaps the contents of `lhs` and `rhs`. Equivalent to `lhs.swap(rhs)`. | | | | --- | --- | | 1) This overload participates in overload resolution only if `[std::is\_swappable\_v](http://en.cppreference.com/w/cpp/types/is_swappable)<Ti>` is `true` for all i from 0 to `sizeof...(Types)`. 2) This overload participates in overload resolution only if `[std::is\_swappable\_v](http://en.cppreference.com/w/cpp/types/is_swappable)<const Ti>` is `true` for all i from 0 to `sizeof...(Types)`. | (since C++17) | ### Parameters | | | | | --- | --- | --- | | lhs, rhs | - | tuples whose contents to swap | ### Return value (none). ### Exceptions [`noexcept`](../../language/noexcept_spec "cpp/language/noexcept spec") specification: `noexcept(noexcept(lhs.swap(rhs)))` ### Example ``` #include <iostream> #include <string> #include <tuple> int main() { std::tuple<int, std::string, float> p1{42, "ABCD", 2.71}, p2; p2 = std::make_tuple(10, "1234", 3.14); auto print_p1_p2 = [&](auto rem) { std::cout << rem << "p1 = {" << std::get<0>(p1) << ", " << std::get<1>(p1) << ", " << std::get<2>(p1) << "}, " << "p2 = {" << std::get<0>(p2) << ", " << std::get<1>(p2) << ", " << std::get<2>(p2) << "}\n"; }; print_p1_p2("Before p1.swap(p2): "); p1.swap(p2); print_p1_p2("After p1.swap(p2): "); swap(p1, p2); print_p1_p2("After swap(p1, p2): "); } ``` Output: ``` Before p1.swap(p2): p1 = {42, ABCD, 2.71}, p2 = {10, 1234, 3.14} After p1.swap(p2): p1 = {10, 1234, 3.14}, p2 = {42, ABCD, 2.71} After swap(p1, p2): p1 = {42, ABCD, 2.71}, p2 = {10, 1234, 3.14} ``` ### See also | | | | --- | --- | | [swap](swap "cpp/utility/tuple/swap") (C++11) | swaps the contents of two `tuple`s (public member function) | | [std::swap(std::pair)](../pair/swap2 "cpp/utility/pair/swap2") (C++11) | specializes the `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) |
programming_docs
cpp std::tuple<Types...>::operator= std::tuple<Types...>::operator= =============================== | | | | | --- | --- | --- | | | (1) | | | ``` tuple& operator=( const tuple& other ); ``` | (since C++11) (until C++20) | | ``` constexpr tuple& operator=( const tuple& other ); ``` | (since C++20) | | ``` constexpr const tuple& operator=( const tuple& other ) const; ``` | (2) | (since C++23) | | | (3) | | | ``` tuple& operator=( tuple&& other ) noexcept(/* see below */); ``` | (since C++11) (until C++20) | | ``` constexpr tuple& operator=( tuple&& other ) noexcept(/* see below */); ``` | (since C++20) | | ``` constexpr const tuple& operator=( tuple&& other ) const; ``` | (4) | (since C++23) | | | (5) | | | ``` template< class... UTypes > tuple& operator=( const tuple<UTypes...>& other ); ``` | (since C++11) (until C++20) | | ``` template< class... UTypes > constexpr tuple& operator=( const tuple<UTypes...>& other ); ``` | (since C++20) | | ``` template< class... UTypes > constexpr const tuple& operator=( const tuple<UTypes...>& other ) const; ``` | (6) | (since C++23) | | | (7) | | | ``` template< class... UTypes > tuple& operator=( tuple<UTypes...>&& other ); ``` | (since C++11) (until C++20) | | ``` template< class... UTypes > constexpr tuple& operator=( tuple<UTypes...>&& other ); ``` | (since C++20) | | ``` template< class... UTypes > constexpr const tuple& operator=( tuple<UTypes...>&& other ) const; ``` | (8) | (since C++23) | | | (9) | | | ``` template< class U1, class U2 > tuple& operator=( const std::pair<U1, U2>& p ); ``` | (since C++11) (until C++20) | | ``` template< class U1, class U2 > constexpr tuple& operator=( const std::pair<U1, U2>& p ); ``` | (since C++20) | | ``` template< class U1, class U2 > constexpr const tuple& operator=( const std::pair<U1, U2>& p ) const; ``` | (10) | (since C++23) | | | (11) | | | ``` template< class U1, class U2 > tuple& operator=( std::pair<U1, U2>&& p ); ``` | (since C++11) (until C++20) | | ``` template< class U1, class U2 > constexpr tuple& operator=( std::pair<U1, U2>&& p ); ``` | (since C++20) | | ``` template< class U1, class U2 > constexpr const tuple& operator=( std::pair<U1, U2>&& p ) const; ``` | (12) | (since C++23) | Replaces the contents of the tuple with the contents of another tuple or a pair. 1) Copy assignment operator. Assigns each element of `other` to the corresponding element of `*this`. * This overload is defined as deleted unless `[std::is\_copy\_assignable](http://en.cppreference.com/w/cpp/types/is_copy_assignable)<T_i>::value` is `true` for all `T_i` in `Types`. 2) Copy assignment operator for const-qualified operand. Assigns each element of `other` to the corresponding element of `*this`. * This overload participates in overload resolution only if `[std::is\_copy\_assignable\_v](http://en.cppreference.com/w/cpp/types/is_copy_assignable)<const T_i>` is `true` for all `T_i` in `Types`. 3) Move assignment operator. For all `i`, assigns `[std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Ti>([std::get](http://en.cppreference.com/w/cpp/utility/variant/get)<i>(other))` to `[std::get](http://en.cppreference.com/w/cpp/utility/variant/get)<i>(\*this)`. * This overload participates in overload resolution only if `[std::is\_move\_assignable](http://en.cppreference.com/w/cpp/types/is_move_assignable)<T_i>::value` is `true` for all `T_i` in `Types`. 4) Move assignment operator const-qualified operand. For all `i`, assigns `[std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Ti>([std::get](http://en.cppreference.com/w/cpp/utility/variant/get)<i>(other))` to `[std::get](http://en.cppreference.com/w/cpp/utility/variant/get)<i>(\*this)`. * This overload participates in overload resolution only if `[std::is\_assignable\_v](http://en.cppreference.com/w/cpp/types/is_assignable)<const T_i&, T_i>` is `true` for all `T_i` in `Types`. 5) For all `i`, assigns `[std::get](http://en.cppreference.com/w/cpp/utility/variant/get)<i>(other)` to `[std::get](http://en.cppreference.com/w/cpp/utility/variant/get)<i>(\*this)`. * This overload participates in overload resolution only if `sizeof...(UTypes) == sizeof...(Types)` and `[std::is\_assignable](http://en.cppreference.com/w/cpp/types/is_assignable)<T_i&, const U_i&>::value` is `true` for all corresponding pairs of types `T_i` in `Types` and `U_i` in `UTypes`. 6) For all `i`, assigns `[std::get](http://en.cppreference.com/w/cpp/utility/variant/get)<i>(other)` to `[std::get](http://en.cppreference.com/w/cpp/utility/variant/get)<i>(\*this)`. * This overload participates in overload resolution only if `sizeof...(UTypes) == sizeof...(Types)` and `[std::is\_assignable\_v](http://en.cppreference.com/w/cpp/types/is_assignable)<const T_i&, const U_i&>` is `true` for all corresponding pairs of types `T_i` in `Types` and `U_i` in `UTypes`. 7) For all `i`, assigns `[std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Ui>([std::get](http://en.cppreference.com/w/cpp/utility/variant/get)<i>(other))` to `[std::get](http://en.cppreference.com/w/cpp/utility/variant/get)<i>(\*this)`. * This overload participates in overload resolution only if `sizeof...(UTypes) == sizeof...(Types)` and `[std::is\_assignable](http://en.cppreference.com/w/cpp/types/is_assignable)<T_i&, U_i>::value` is `true` for all corresponding pairs of types `T_i` in `Types` and `U_i` in `UTypes`. 8) For all `i`, assigns `[std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Ui>([std::get](http://en.cppreference.com/w/cpp/utility/variant/get)<i>(other))` to `[std::get](http://en.cppreference.com/w/cpp/utility/variant/get)<i>(\*this)`. * This overload participates in overload resolution only if `sizeof...(UTypes) == sizeof...(Types)` and `[std::is\_assignable\_v](http://en.cppreference.com/w/cpp/types/is_assignable)<const T_i&, U_i>` is `true` for all corresponding pairs of types `T_i` in `Types` and `U_i` in `UTypes`. 9) Assigns `p.first` to the first element of `*this` and `p.second` to the second element of `*this`. * This overload participates in overload resolution only if `sizeof...(Types) == 2`, `[std::is\_assignable](http://en.cppreference.com/w/cpp/types/is_assignable)<T_0&, const U1&>::value` and `[std::is\_assignable](http://en.cppreference.com/w/cpp/types/is_assignable)<T_1&, const U2&>::value` are both `true`, where `T_0` and `T_1` are the two types constituting `Types`. 10) Assigns `p.first` to the first element of `*this` and `p.second` to the second element of `*this`. * This overload participates in overload resolution only if `sizeof...(Types) == 2`, `[std::is\_assignable\_v](http://en.cppreference.com/w/cpp/types/is_assignable)<const T_0&, const U1&>` and `[std::is\_assignable\_v](http://en.cppreference.com/w/cpp/types/is_assignable)<const T_1&, const U2&>` are both `true`, where `T_0` and `T_1` are the two types constituting `Types`. 11) Assigns `[std::forward](http://en.cppreference.com/w/cpp/utility/forward)<U1>(p.first)` to the first element of `*this` and `[std::forward](http://en.cppreference.com/w/cpp/utility/forward)<U2>(p.second)` to the second element of `*this`. * This overload participates in overload resolution only if `[std::is\_assignable](http://en.cppreference.com/w/cpp/types/is_assignable)<T_0&, U1>::value` and `[std::is\_assignable](http://en.cppreference.com/w/cpp/types/is_assignable)<T_1&, U2>::value` are both `true`, where `T_0` and `T_1` are the two types constituting `Types`. 12) Assigns `[std::forward](http://en.cppreference.com/w/cpp/utility/forward)<U1>(p.first)` to the first element of `*this` and `[std::forward](http://en.cppreference.com/w/cpp/utility/forward)<U2>(p.second)` to the second element of `*this`. * This overload participates in overload resolution only if `[std::is\_assignable](http://en.cppreference.com/w/cpp/types/is_assignable)<const T_0&, U1>` and `[std::is\_assignable\_v](http://en.cppreference.com/w/cpp/types/is_assignable)<const T_1&, U2>` are both `true`, where `T_0` and `T_1` are the two types constituting `Types`. ### Parameters | | | | | --- | --- | --- | | other | - | tuple to replace the contents of this tuple | | p | - | pair to replace the contents of this 2-tuple | ### Return value `*this`. ### Exceptions 1,2) May throw implementation-defined exceptions. 3) [`noexcept`](../../language/noexcept_spec "cpp/language/noexcept spec") specification: `noexcept( [std::is\_nothrow\_move\_assignable](http://en.cppreference.com/w/cpp/types/is_move_assignable)<T0>::value && [std::is\_nothrow\_move\_assignable](http://en.cppreference.com/w/cpp/types/is_move_assignable)<T1>::value && [std::is\_nothrow\_move\_assignable](http://en.cppreference.com/w/cpp/types/is_move_assignable)<T2>::value && ... )` 4-12) May throw implementation-defined exceptions. ### Example ``` #include <iostream> #include <string> #include <tuple> #include <utility> #include <vector> // helper function to print std::vector template<class Os, class T> Os& operator<< (Os& os, std::vector<T> const& v) { os << "{"; for (std::size_t t = 0; t != v.size(); ++t) os << v[t] << (t+1 < v.size() ? ",":""); return os << "}"; } // helpers to print a tuple of any size template<class Os, class... Args> Os& operator<< (Os& os, const std::tuple<Args...>& t) { os << "{ "; std::apply([&](auto&& arg, auto&&... args) { os << arg; ((os << ", " << args), ...); }, t); return os << " }"; } struct line { int len{60}; }; template<class Os> Os& operator<< (Os& os, line l) { while (l.len-- > 0) std::cout << "─"; return os << '\n'; } int main() { // Tuple to tuple examples // std::tuple<int, std::string, std::vector<int>> t1{1, "alpha", {1, 2, 3} }, t2{2, "beta", {4, 5} }; // Normal copy assignment // operator=( const tuple& other ); std::cout << "t1 = " << t1 << ", t2 = " << t2 << '\n'; t1 = t2; std::cout << "t1 = t2;\n" "t1 = " << t1 << ", t2 = " << t2 << '\n' << line{}; // Normal move assignment // operator=( tuple&& other ); t1 = std::move(t2); std::cout << "t1 = std::move(t2);\n" "t1 = " << t1 << ", t2 = " << t2 << '\n' << line{}; // Converting copy assignment // operator=( const tuple<UTypes...>& other ); std::tuple<short, const char*, std::vector<int>> t3{3, "gamma", {6,7,8} }; t1 = t3; std::cout << "t1 = t3; \n" "t1 = " << t1 << ", t3 = " << t3 << '\n' << line{}; // Converting move assignment // operator=( tuple<UTypes...>&& other ); t1 = std::move(t3); std::cout << "t1 = std::move(t3);\n" "t1 = " << t1 << ", t3 = " << t3 << '\n' << line{}; // Pair to tuple examples // std::tuple<std::string, std::vector<int>> t4{"delta", {10,11,12} }; std::pair<const char*, std::vector<int>> p1{"epsilon", {14,15,16} }; // Converting copy assignment from std::pair // operator=( const std::pair<U1,U2>& p ); std::cout << "t4 = " << t4 << ", " << "p1 = { " << p1.first << ", " << p1.second << " };\n"; t4 = p1; std::cout << "t4 = p1;\n" "t4 = " << t4 << ", p1 = { " << p1.first << ", " << p1.second << " };\n" << line{}; // Converting move assignment from std::pair // operator=( std::pair<U1,U2>&& p ); t4 = std::move(p1); std::cout << "t4 = std::move(p1);\n" "t4 = " << t4 << ", p1 = { " << p1.first << ", " << p1.second << " };\n" << line{}; #ifdef __cpp_lib_ranges_zip // Const tuple-of-proxies assignment example std::vector<bool> v({false, true}); const std::tuple<std::vector<bool>::reference> t0_const{v[0]}, t1_const{v[1]}; t0_const = t1_const; std::cout << std::boolalpha << "t0_const = t1_const;\n" "t0_const = " << t0_const << ", t1_const = " << t1_const << '\n'; #endif } ``` Possible output: ``` t1 = { 1, alpha, {1,2,3} }, t2 = { 2, beta, {4,5} } t1 = t2; t1 = { 2, beta, {4,5} }, t2 = { 2, beta, {4,5} } ──────────────────────────────────────────────────────────── t1 = std::move(t2); t1 = { 2, beta, {4,5} }, t2 = { 2, , {} } ──────────────────────────────────────────────────────────── t1 = t3; t1 = { 3, gamma, {6,7,8} }, t3 = { 3, gamma, {6,7,8} } ──────────────────────────────────────────────────────────── t1 = std::move(t3); t1 = { 3, gamma, {6,7,8} }, t3 = { 3, gamma, {} } ──────────────────────────────────────────────────────────── t4 = { delta, {10,11,12} }, p1 = { epsilon, {14,15,16} }; t4 = p1; t4 = { epsilon, {14,15,16} }, p1 = { epsilon, {14,15,16} }; ──────────────────────────────────────────────────────────── t4 = std::move(p1); t4 = { epsilon, {14,15,16} }, p1 = { epsilon, {} }; ──────────────────────────────────────────────────────────── t0_const = t1_const; t0_const = { true }, t1_const = { true } ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 2729](https://cplusplus.github.io/LWG/issue2729) | C++11 | `tuple::operator=` was unconstrained and mightresult in unnecessary undefined behavior | constrained | ### See also | | | | --- | --- | | [(constructor)](tuple "cpp/utility/tuple/tuple") (C++11) | constructs a new `tuple` (public member function) | | [operator=](../pair/operator= "cpp/utility/pair/operator=") | assigns the contents (public member function of `std::pair<T1,T2>`) | cpp std::make_tuple std::make\_tuple ================ | Defined in header `[<tuple>](../../header/tuple "cpp/header/tuple")` | | | | --- | --- | --- | | ``` template< class... Types > std::tuple<VTypes...> make_tuple( Types&&... args ); ``` | | (since C++11) (constexpr since C++14) | Creates a tuple object, deducing the target type from the types of arguments. For each `Ti` in `Types...`, the corresponding type `Vi` in `VTypes...` is `[std::decay](http://en.cppreference.com/w/cpp/types/decay)<Ti>::type` unless application of `[std::decay](../../types/decay "cpp/types/decay")` results in `[std::reference\_wrapper](http://en.cppreference.com/w/cpp/utility/functional/reference_wrapper)<X>` for some type `X`, in which case the deduced type is `X&`. ### Parameters | | | | | --- | --- | --- | | args | - | zero or more arguments to construct the tuple from | ### Return value A `[std::tuple](../tuple "cpp/utility/tuple")` object containing the given values, created as if by `[std::tuple](http://en.cppreference.com/w/cpp/utility/tuple)<VTypes...>([std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Types>(t)...).` ### Possible implementation | | | --- | | ``` template <class T> struct unwrap_refwrapper { using type = T; }; template <class T> struct unwrap_refwrapper<std::reference_wrapper<T>> { using type = T&; }; template <class T> using unwrap_decay_t = typename unwrap_refwrapper<typename std::decay<T>::type>::type; // or use std::unwrap_ref_decay_t (since C++20) template <class... Types> constexpr // since C++14 std::tuple<unwrap_decay_t<Types>...> make_tuple(Types&&... args) { return std::tuple<unwrap_decay_t<Types>...>(std::forward<Types>(args)...); } ``` | ### Example ``` #include <iostream> #include <tuple> #include <functional> std::tuple<int, int> f() // this function returns multiple values { int x = 5; return std::make_tuple(x, 7); // return {x,7}; in C++17 } int main() { // heterogeneous tuple construction int n = 1; auto t = std::make_tuple(10, "Test", 3.14, std::ref(n), n); n = 7; std::cout << "The value of t is " << "(" << std::get<0>(t) << ", " << std::get<1>(t) << ", " << std::get<2>(t) << ", " << std::get<3>(t) << ", " << std::get<4>(t) << ")\n"; // function returning multiple values int a, b; std::tie(a, b) = f(); std::cout << a << " " << b << "\n"; } ``` Output: ``` The value of t is (10, Test, 3.14, 7, 1) 5 7 ``` ### See also | | | | --- | --- | | [tie](tie "cpp/utility/tuple/tie") (C++11) | creates a `[tuple](../tuple "cpp/utility/tuple")` of lvalue references or unpacks a tuple into individual objects (function template) | | [forward\_as\_tuple](forward_as_tuple "cpp/utility/tuple/forward as tuple") (C++11) | creates a `tuple` of [forwarding references](../../language/reference#Forwarding_references "cpp/language/reference") (function template) | | [tuple\_cat](tuple_cat "cpp/utility/tuple/tuple cat") (C++11) | creates a `tuple` by concatenating any number of tuples (function template) | | [apply](../apply "cpp/utility/apply") (C++17) | calls a function with a tuple of arguments (function template) | cpp operator==,!=,<,<=,>,>=,<=>(std::tuple) operator==,!=,<,<=,>,>=,<=>(std::tuple) ======================================= | Defined in header `[<tuple>](../../header/tuple "cpp/header/tuple")` | | | | --- | --- | --- | | | (1) | | | ``` template< class... TTypes, class... UTypes > bool operator==( const std::tuple<TTypes...>& lhs, const std::tuple<UTypes...>& rhs ); ``` | (since C++11) (until C++14) | | ``` template< class... TTypes, class... UTypes > constexpr bool operator==( const std::tuple<TTypes...>& lhs, const std::tuple<UTypes...>& rhs ); ``` | (since C++14) | | | (2) | | | ``` template< class... TTypes, class... UTypes > bool operator!=( const std::tuple<TTypes...>& lhs, const std::tuple<UTypes...>& rhs ); ``` | (since C++11) (until C++14) | | ``` template< class... TTypes, class... UTypes > constexpr bool operator!=( const std::tuple<TTypes...>& lhs, const std::tuple<UTypes...>& rhs ); ``` | (since C++14) (until C++20) | | | (3) | | | ``` template< class... TTypes, class... UTypes > bool operator<( const std::tuple<TTypes...>& lhs, const std::tuple<UTypes...>& rhs ); ``` | (since C++11) (until C++14) | | ``` template< class... TTypes, class... UTypes > constexpr bool operator<( const std::tuple<TTypes...>& lhs, const std::tuple<UTypes...>& rhs ); ``` | (since C++14) (until C++20) | | | (4) | | | ``` template< class... TTypes, class... UTypes > bool operator<=( const std::tuple<TTypes...>& lhs, const std::tuple<UTypes...>& rhs ); ``` | (since C++11) (until C++14) | | ``` template< class... TTypes, class... UTypes > constexpr bool operator<=( const std::tuple<TTypes...>& lhs, const std::tuple<UTypes...>& rhs ); ``` | (since C++14) (until C++20) | | | (5) | | | ``` template< class... TTypes, class... UTypes > bool operator>( const std::tuple<TTypes...>& lhs, const std::tuple<UTypes...>& rhs ); ``` | (since C++11) (until C++14) | | ``` template< class... TTypes, class... UTypes > constexpr bool operator>( const std::tuple<TTypes...>& lhs, const std::tuple<UTypes...>& rhs ); ``` | (since C++14) (until C++20) | | | (6) | | | ``` template< class... TTypes, class... UTypes > bool operator>=( const std::tuple<TTypes...>& lhs, const std::tuple<UTypes...>& rhs ); ``` | (since C++11) (until C++14) | | ``` template< class... TTypes, class... UTypes > constexpr bool operator>=( const std::tuple<TTypes...>& lhs, const std::tuple<UTypes...>& rhs ); ``` | (since C++14) (until C++20) | | ``` template< class... TTypes, class... UTypes > constexpr /* see below */ operator<=>( const std::tuple<TTypes...>& lhs, const std::tuple<UTypes...>& rhs ); ``` | (7) | (since C++20) | 1-2) Compares every element of the tuple `lhs` with the corresponding element of the tuple `rhs`. 3-6) Compares `lhs` and `rhs` lexicographically by `operator<`, that is, compares the first elements, if they are equivalent, compares the second elements, if those are equivalent, compares the third elements, and so on. For non-empty tuples, (3) is equivalent to. ``` if (std::get<0>(lhs) < std::get<0>(rhs)) return true; if (std::get<0>(rhs) < std::get<0>(lhs)) return false; if (std::get<1>(lhs) < std::get<1>(rhs)) return true; if (std::get<1>(rhs) < std::get<1>(lhs)) return false; ... return std::get<N - 1>(lhs) < std::get<N - 1>(rhs); ``` 7) Compares `lhs` and `rhs` lexicographically by *synthesized three-way comparison* (see below), that is, compares the first elements, if they are equivalent, compares the second elements, if those are equivalent, compares the third elements, and so on. The return type is the [common comparison category type](../compare/common_comparison_category "cpp/utility/compare/common comparison category") of results of synthesized three-way comparison on every pair of element in `lhs` and `rhs`. For empty tuples, the return type is `std::strong_ordering`. For non-empty tuples, (7) is equivalent to. ``` if (auto c = synth_three_way(std::get<0>(lhs), std::get<0>(rhs)); c != 0) return c; if (auto c = synth_three_way(std::get<1>(lhs), std::get<1>(rhs)); c != 0) return c; ... return synth_three_way(std::get<N - 1>(lhs), std::get<N - 1>(rhs)); ``` where *`synth_three_way`* is an exposition-only function object performing synthesized three-way comparison. `sizeof...(TTypes)` and `sizeof...(UTypes)` must be equal, otherwise the program is ill-formed or for `operator<=>`, the operator function does not participate in overload resolution (since C++20). `N` in above code is equal to both. All comparison operators are short-circuited; they do not access tuple elements beyond what is necessary to determine the result of the comparison. | | | | --- | --- | | The `<`, `<=`, `>`, `>=`, and `!=` operators are [synthesized](../../language/operators#Relational_operators "cpp/language/operators") from `operator<=>` and `operator==` respectively. | (since C++20) | | | | | --- | --- | | Synthesized three-way comparison Given two object types `T` and `U`, a `const T` lvalue `t` as left hand operand, a `const U` lvalue `u` is right hand operand, *synthesized three-way comparison* is defined as:* if `[std::three\_way\_comparable\_with](http://en.cppreference.com/w/cpp/utility/compare/three_way_comparable)<T, U>` is satisfied, equivalent to `t <=> u`; * otherwise, if comparing a `const T` lvalue with a `const U` lvalue in both orders are well-formed and the result types satisfies *`boolean-testable`*, equivalent to ``` t < u ? std::weak_ordering::less : u < t ? std::weak_ordering::greater : std::weak_ordering::equivalent ``` * otherwise, synthesized three-way comparison is not defined, which makes `operator<=>` do not participate in overload resolution. The behavior of `operator<=>` is undefined if [`three_way_comparable_with`](../compare/three_way_comparable "cpp/utility/compare/three way comparable") or *`boolean-testable`* is satisfied but not modeled. | (since C++20) | ### Parameters | | | | | --- | --- | --- | | lhs, rhs | - | tuples to compare | ### Return value 1) `true` if `[std::get](http://en.cppreference.com/w/cpp/utility/variant/get)<i>(lhs) == [std::get](http://en.cppreference.com/w/cpp/utility/variant/get)<i>(rhs)` for all i in `[0, sizeof...(Types))`, otherwise `false`. For two empty tuples returns `true`. 2) `!(lhs == rhs)` 3) `true` if the first non-equivalent element in `lhs` is less than the one in `rhs`, `false` if the first non-equivalent element in `rhs` is less than the one in `lhs` or there is no non-equivalent element. For two empty tuples, returns `false`. 4) `!(rhs < lhs)` 5) `rhs < lhs` 6) `!(lhs < rhs)` 7) The relation between the first pair of non-equivalent elements if there is any, `std::strong_ordering::equal` otherwise. For two empty tuples, returns `std::strong_ordering::equal`. ### Example Because operator< is defined for tuples, containers of tuples can be sorted. ``` #include <iostream> #include <tuple> #include <vector> #include <algorithm> int main() { std::vector<std::tuple<int, std::string, float>> v{ {2, "baz", -0.1}, {2, "bar", 3.14}, {1, "foo", 10.1}, {2, "baz", -1.1}, }; std::sort(v.begin(), v.end()); for(const auto& p: v) { std::cout << "{" << std::get<0>(p) << ", " << std::get<1>(p) << ", " << std::get<2>(p) << "}\n"; } } ``` Output: ``` {1, foo, 10.1} {2, bar, 3.14} {2, baz, -1.1} {2, baz, -0.1} ``` ### See also | | | | --- | --- | | [operator==operator!=operator<operator<=operator>operator>=operator<=>](../pair/operator_cmp "cpp/utility/pair/operator cmp") (removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(C++20) | lexicographically compares the values in the pair (function template) |
programming_docs
cpp std::get(std::tuple) std::get(std::tuple) ==================== | Defined in header `[<tuple>](../../header/tuple "cpp/header/tuple")` | | | | --- | --- | --- | | ``` template< std::size_t I, class... Types > typename std::tuple_element<I, tuple<Types...> >::type& get( tuple<Types...>& t ) noexcept; ``` | (1) | (since C++11) (constexpr since C++14) | | ``` template< std::size_t I, class... Types > typename std::tuple_element<I, tuple<Types...> >::type&& get( tuple<Types...>&& t ) noexcept; ``` | (2) | (since C++11) (constexpr since C++14) | | ``` template< std::size_t I, class... Types > typename std::tuple_element<I, tuple<Types...> >::type const& get( const tuple<Types...>& t ) noexcept; ``` | (3) | (since C++11) (constexpr since C++14) | | ``` template< std::size_t I, class... Types > typename std::tuple_element<I, tuple<Types...> >::type const&& get( const tuple<Types...>&& t ) noexcept; ``` | (4) | (since C++11) (constexpr since C++14) | | ``` template< class T, class... Types > constexpr T& get( tuple<Types...>& t ) noexcept; ``` | (5) | (since C++14) | | ``` template< class T, class... Types > constexpr T&& get( tuple<Types...>&& t ) noexcept; ``` | (6) | (since C++14) | | ``` template< class T, class... Types > constexpr const T& get( const tuple<Types...>& t ) noexcept; ``` | (7) | (since C++14) | | ``` template< class T, class... Types > constexpr const T&& get( const tuple<Types...>&& t ) noexcept; ``` | (8) | (since C++14) | 1-4) Extracts the `Ith` element from the tuple. `I` must be an integer value in `[0, sizeof...(Types))`. 5-8) Extracts the element of the tuple `t` whose type is `T`. Fails to compile unless the tuple has exactly one element of that type. ### Parameters | | | | | --- | --- | --- | | t | - | tuple whose contents to extract | ### Return value A reference to the selected element of `t`. ### Notes | [Feature-test](../feature_test "cpp/utility/feature test") macro | Value | Std | Comment | | --- | --- | --- | --- | | [`__cpp_lib_tuples_by_type`](../../feature_test#Library_features "cpp/feature test") | `201304L` | (C++14) | for type-based access | ### Example ``` #include <iostream> #include <string> #include <tuple> int main() { auto t = std::make_tuple(1, "Foo", 3.14); // index-based access std::cout << "(" << std::get<0>(t) << ", " << std::get<1>(t) << ", " << std::get<2>(t) << ")\n"; // type-based access (C++14 or later) std::cout << "(" << std::get<int>(t) << ", " << std::get<const char*>(t) << ", " << std::get<double>(t) << ")\n"; // Note: std::tie and structured binding may also be used to decompose a tuple } ``` Output: ``` (1, Foo, 3.14) (1, Foo, 3.14) ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 2485](https://cplusplus.github.io/LWG/issue2485) | C++11 (by index)C++14 (by type) | there are no overloads for const tuple&& | the overloads are added | ### See also | | | | --- | --- | | [Structured binding](../../language/structured_binding "cpp/language/structured binding") (C++17) | binds the specified names to sub-objects or tuple elements of the initializer | | [std::get(std::array)](../../container/array/get "cpp/container/array/get") (C++11) | accesses an element of an `array` (function template) | | [std::get(std::pair)](../pair/get "cpp/utility/pair/get") (C++11) | accesses an element of a `pair` (function template) | | [std::get(std::variant)](../variant/get "cpp/utility/variant/get") (C++17) | reads the value of the variant given the index or the type (if the type is unique), throws on error (function template) | | [get(std::ranges::subrange)](../../ranges/subrange/get "cpp/ranges/subrange/get") (C++20) | obtains iterator or sentinel from a `[std::ranges::subrange](../../ranges/subrange "cpp/ranges/subrange")` (function template) | cpp std::expected<T,E>::emplace std::expected<T,E>::emplace =========================== | | | | | --- | --- | --- | | T is not *cv* void | | | | ``` template< class... Args > constexpr T& emplace( Args&&... args ) noexcept; ``` | (1) | (since C++23) | | ``` template< class U, class... Args > constexpr T& emplace( std::initializer_list<U>& il, Args&&... args ) noexcept; ``` | (2) | (since C++23) | | T is *cv* void | | | | ``` constexpr void emplace() noexcept; ``` | (3) | (since C++23) | Constructs an expected value in-place. After the call, [`has_value()`](operator_bool "cpp/utility/expected/operator bool") returns true. 1) Destroys the contained value, then initializes the expected value contained in `*this` as if by [direct-initializing](../../language/direct_initialization "cpp/language/direct initialization") an object of type `T` from the arguments `[std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Args>(args)...`. This overload participates in overload resolution only if `[std::is\_nothrow\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_constructible)<T, Args...>` is true. 2) Destroys the contained value, then initializes the expected value contained in `*this` as if by [direct-initializing](../../language/direct_initialization "cpp/language/direct initialization") an object of type `T` from the arguments `il, [std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Args>(args)...`. This overload participates in overload resolution only if `[std::is\_nothrow\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_constructible)<T, [std::initializer\_list](http://en.cppreference.com/w/cpp/utility/initializer_list)<U>&, Args...>` is true. 3) If `*this` contains an unexpected value, destroys that value. ### Parameters | | | | | --- | --- | --- | | args... | - | the arguments to pass to the constructor | | il | - | the initializer list to pass to the constructor | ### Return value A reference to the new contained value. ### Exceptions [`noexcept`](../../language/noexcept_spec "cpp/language/noexcept spec") specification: `noexcept` ### Notes If the construction of `T` is potentially-throwing, this function is not defined. In this case, it is the responsibility of the user to create a temporary and move or copy it. ### Example ### See also | | | | --- | --- | | [operator=](operator= "cpp/utility/expected/operator=") | assigns contents (public member function) | cpp std::expected<T,E>::~expected std::expected<T,E>::~expected ============================= | | | | | --- | --- | --- | | ``` constexpr ~expected(); ``` | | (since C++23) | Destroys the currently contained value. That is, if [`has_value()`](https://en.cppreference.com/mwiki/index.php?title=cpp/utility/expected/%7Eexpected/operator_bool&action=edit&redlink=1 "cpp/utility/expected/~expected/operator bool (page does not exist)") is false, destroys the unexpected value; otherwise, if `T` is not (possibly cv-qualified) `void`, destroys the expected value. This destructor is trivial if. * either `T` is (possibly cv-qualified) `void`, or `[std::is\_trivially\_destructible\_v](http://en.cppreference.com/w/cpp/types/is_destructible)<T>` is true, and * `[std::is\_trivially\_destructible\_v](http://en.cppreference.com/w/cpp/types/is_destructible)<E>` is true. ### Example cpp std::expected<T,E>::swap std::expected<T,E>::swap ======================== | | | | | --- | --- | --- | | ``` constexpr void swap( expected& other ) noexcept(/*see below*/); ``` | | (since C++23) | Swaps the contents with those of `other`. * If both [`this->has_value()`](operator_bool "cpp/utility/expected/operator bool") and `other.has_value()` are true: + If `T` is (possibly cv-qualified) `void`, no effects. + Otherwise, equivalent to `using [std::swap](http://en.cppreference.com/w/cpp/algorithm/swap); swap(\*\*this, \*other);`. * If both `this->has_value()` and `other.has_value()` are false, equivalent to `using [std::swap](http://en.cppreference.com/w/cpp/algorithm/swap); swap(this->error(), other.error());`. * If `this->has_value()` is false and `other.has_value()` is true, calls `other.swap(*this)`. * If `this->has_value()` is true and `other.has_value()` is false, + If `T` is (possibly cv-qualified) `void`, let *unex* be the member that represents the unexpected value, equivalent to: ``` std::construct_at(std::addressof(unex), std::move(other.unex)); std::destroy_at(std::addressof(other.unex)); ``` * Otherwise, let *val* be the member that represents the expected value and *unex* be the member that represents the unexpected value, equivalent to: ``` if constexpr (std::is_nothrow_move_constructible_v<E>) { E temp(std::move(other.unex)); std::destroy_at(std::addressof(other.unex)); try { std::construct_at(std::addressof(other.val), std::move(val)); std::destroy_at(std::addressof(val)); std::construct_at(std::addressof(unex), std::move(temp)); } catch(...) { std::construct_at(std::addressof(other.unex), std::move(temp)); throw; } } else { T temp(std::move(val)); std::destroy_at(std::addressof(val)); try { std::construct_at(std::addressof(unex), std::move(other.unex)); std::destroy_at(std::addressof(other.unex)); std::construct_at(std::addressof(other.val), std::move(temp)); } catch(...) { std::construct_at(std::addressof(val), std::move(temp)); throw; } } ``` This function participates in overload resolution only if. * either `T` is (possibly cv-qualified) `void`, or `[std::is\_swappable\_v](http://en.cppreference.com/w/cpp/types/is_swappable)<T>` is true, and * `[std::is\_swappable\_v](http://en.cppreference.com/w/cpp/types/is_swappable)<E>` is true, and * either `T` is (possibly cv-qualified) `void`, or `[std::is\_move\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_move_constructible)<T>` is true, and * `[std::is\_move\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_move_constructible)<E>` is true, and * at least one of the following is true: + `T` is (possibly cv-qualified) `void` + `[std::is\_nothrow\_move\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_move_constructible)<T>` + `[std::is\_nothrow\_move\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_move_constructible)<E>` ### Parameters | | | | | --- | --- | --- | | other | - | the `optional` object to exchange the contents with | ### Return value (none). ### Exceptions If `T` is (possibly cv-qualified) `void`, [`noexcept`](../../language/noexcept_spec "cpp/language/noexcept spec") specification: `noexcept( [std::is\_nothrow\_move\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_move_constructible)<E> && [std::is\_nothrow\_swappable\_v](http://en.cppreference.com/w/cpp/types/is_swappable)<E> )` Otherwise, [`noexcept`](../../language/noexcept_spec "cpp/language/noexcept spec") specification: `noexcept( [std::is\_nothrow\_move\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_move_constructible)<T> && [std::is\_nothrow\_swappable\_v](http://en.cppreference.com/w/cpp/types/is_swappable)<T> && [std::is\_nothrow\_move\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_move_constructible)<E> && [std::is\_nothrow\_swappable\_v](http://en.cppreference.com/w/cpp/types/is_swappable)<E> )` In the case of thrown exception, the states of the contained values of `*this` and `other` are determined by the exception safety guarantees of `swap` or `T`'s and `E`'s move constructor, whichever is called. For both `*this` and `other`, if the object contained an expected value, it is left containing an expected value, and the other way round. ### Example ### See also | | | | --- | --- | | [swap(std::expected)](swap2 "cpp/utility/expected/swap2") (C++23) | specializes the `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` algorithm (function) | cpp std::expected<T,E>::operator->, std::expected<T,E>::operator* std::expected<T,E>::operator->, std::expected<T,E>::operator\* ============================================================== | | | | | --- | --- | --- | | T is not *cv* void | | | | ``` constexpr const T* operator->() const noexcept; ``` | (1) | (since C++23) | | ``` constexpr T* operator->() noexcept; ``` | (1) | (since C++23) | | ``` constexpr const T& operator*() const& noexcept; ``` | (2) | (since C++23) | | ``` constexpr T& operator*() & noexcept; ``` | (2) | (since C++23) | | ``` constexpr const T&& operator*() const&& noexcept; ``` | (2) | (since C++23) | | ``` constexpr T&& operator*() && noexcept; ``` | (2) | (since C++23) | | T is *cv* void | | | | ``` constexpr void operator*() const noexcept; ``` | (3) | (since C++23) | Accesses the expected value contained in `*this`. 1) Returns a pointer to the contained value. 2) Returns a reference to the contained value. 3) Returns nothing. The behavior is undefined if [`this->has_value()`](operator_bool "cpp/utility/expected/operator bool") is false. ### Parameters (none). ### Return value Pointer or reference to the contained value. ### Example ### See also | | | | --- | --- | | [value](value "cpp/utility/expected/value") | returns the expected value (public member function) | | [value\_or](value_or "cpp/utility/expected/value or") | returns the expected value if available, another value otherwise (public member function) | | [operator boolhas\_value](operator_bool "cpp/utility/expected/operator bool") | checks whether the object contains an expected value (public member function) | | [error](error "cpp/utility/expected/error") | returns the unexpected value (public member function) | cpp std::bad_expected_access std::bad\_expected\_access ========================== | Defined in header `[<expected>](../../header/expected "cpp/header/expected")` | | | | --- | --- | --- | | ``` template< class E > class bad_expected_access : bad_expected_access<void> ``` | (1) | (since C++23) | | ``` template<> class bad_expected_access<void> : public std::exception ``` | (2) | (since C++23) | 1) Defines a type of object to be thrown by [`std::expected::value`](value "cpp/utility/expected/value") when accessing an expected object that contains an unexpected value. `bad_expected_access<E>` stores a copy of the unexpected value. 2) `bad_expected_access<void>` is the base class of all other `bad_expected_access` specializations. ### Members of the primary template | | | | --- | --- | | **(constructor)** | constructs a `bad_expected_access` object (public member function) | | error | returns the stored value (public member function) | | what | returns the explanatory string (public member function) | std::bad\_expected\_access::bad\_expected\_access -------------------------------------------------- | | | | | --- | --- | --- | | ``` explicit bad_expected_access( E e ); ``` | | (since C++23) | Constructs a new `bad_expected_access<E>` object. Initializes the stored value with `std::move(e)`. std::bad\_expected\_access::error ---------------------------------- | | | | | --- | --- | --- | | ``` const E& error() const& noexcept; E& error() & noexcept; const E&& error() && noexcept; E&& error() && noexcept; ``` | | (since C++23) | Returns a reference to the stored value. std::bad\_expected\_access::what --------------------------------- | | | | | --- | --- | --- | | ``` virtual const char* what() const noexcept; ``` | | (since C++23) | Returns the explanatory string. ### Parameters (none). ### Return value Pointer to a null-terminated string with explanatory information. The string is suitable for conversion and display as a `[std::wstring](../../string/basic_string "cpp/string/basic string")`. The pointer is guaranteed to be valid at least until the exception object from which it is obtained is destroyed, or until a non-const member function (e.g. copy assignment operator) on the exception object is called. ### Notes Implementations are allowed but not required to override `what()`. ### Members of the `bad_expected_access<void>` specialization | | | | --- | --- | | (constructor) | constructs a `bad_expected_access<void>` object (protected member function) | | (destructor) | destroys the `bad_expected_access<void>` object (protected member function) | | operator= | replaces the `bad_expected_access<void>` object (protected member function) | | what | returns the explanatory string (public member function) | Special member functions of `bad_expected_access<void>` are protected. They can only be called by derived classes. ### Example cpp swap(std::expected) swap(std::expected) =================== | | | | | --- | --- | --- | | ``` friend constexpr void swap( expected& lhs, expected& rhs ) noexcept(/*see below*/); ``` | | (since C++23) | Overloads the `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` algorithm for `std::expected`. Exchanges the state of `lhs` with that of `rhs`. Effectively calls `lhs.swap(rhs)`. This overload participates in overload resolution only if `lhs.swap(rhs)` is valid. This function is not visible to ordinary [unqualified](../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../language/adl "cpp/language/adl") when `std::expected<T, E>` is an associated class of the arguments. ### Parameters | | | | | --- | --- | --- | | lhs, rhs | - | `expected` objects whose states to swap | ### Return value (none). ### Exceptions [`noexcept`](../../language/noexcept_spec "cpp/language/noexcept spec") specification: `noexcept(noexcept(lhs.swap(rhs)))` ### Example ### See also | | | | --- | --- | | [swap](swap "cpp/utility/expected/swap") | exchanges the contents (public member function) | cpp std::expected<T,E>::value std::expected<T,E>::value ========================= | | | | | --- | --- | --- | | T is not *cv* void | | | | ``` constexpr T& value() &; ``` | (1) | (since C++23) | | ``` constexpr const T& value() const&; ``` | (2) | (since C++23) | | ``` constexpr T&& value() &&; ``` | (3) | (since C++23) | | ``` constexpr const T&& value() const&&; ``` | (4) | (since C++23) | | T is *cv* void | | | | ``` constexpr void value() const&; ``` | (5) | (since C++23) | | ``` constexpr void value() &&; ``` | (6) | (since C++23) | If `*this` contains an expected value, returns a reference to the contained value. Otherwise, throws a `std::bad_expected_access` exception that contains a copy of the unexpected value contained in `*this`. ### Parameters (none). ### Return value 1-4) A reference to the expected value contained in `*this`. 5-6) (none) ### Exceptions 1-2,5) Throws `std::bad_expected_access(error())` if `*this` contain an unexpected value. 3-4,6) Throws `std::bad_expected_access(std::move(error()))` if `*this` contain an unexpected value. ### Example ### See also | | | | --- | --- | | [value\_or](value_or "cpp/utility/expected/value or") | returns the expected value if available, another value otherwise (public member function) | | [operator->operator\*](operator* "cpp/utility/expected/operator*") | accesses the expected value (public member function) | | [error](error "cpp/utility/expected/error") | returns the unexpected value (public member function) | | [bad\_expected\_access](bad_expected_access "cpp/utility/expected/bad expected access") (C++23) | exception indicating checked access to an expected that contains an unexpected value (class template) |
programming_docs
cpp operator==(std::expected) operator==(std::expected) ========================= | | | | | --- | --- | --- | | ``` template< class T2, class E2 > requires (!std::is_void_v<T2>) friend constexpr bool operator==( const expected& lhs, const std::expected<T2, E2>& rhs ); ``` | (1) | (since C++23) (T is not *cv* void) | | ``` template< class T2, class E2 > requires std::is_void_v<T2> friend constexpr bool operator==( const expected& lhs, const std::expected<T2, E2>& rhs ); ``` | (2) | (since C++23) (T is *cv* void) | | ``` template< class T2 > friend constexpr bool operator==( const expected& x, const T2& val ); ``` | (3) | (since C++23) (T is not *cv* void) | | ``` template< class E2 > friend constexpr bool operator==( const expected& x, const unexpected<E2>& e ); ``` | (4) | (since C++23) | Performs comparison operations on `expected` objects. 1,2) Compares two `expected` objects. The objects compare equal if and only if `lhs.has_value()` and `rhs.has_value()` are equal, and the contained values are equal. * For overload (1), if the expressions `*x == *y` and `x.error() == y.error()` are not well-formed, or if their results are not convertible to `bool`, the program is ill-formed. * For overload (2), if the expressions `x.error() == y.error()` is not well-formed, or if its result is not convertible to `bool`, the program is ill-formed. 3) Compares `expected` object with a value. The objects compare equal if and only if `x` contains an expected value, and the contained value is equal to `val`. * If the expression `*x == val` is not well-formed, or if its result is not convertible to `bool`, the program is ill-formed. 4) Compares `expected` object with an unexpected value. The objects compare equal if and only if `x` contains an unexpected value, and the contained value is equal to `e.error()`. * If the expression `x.error() == e.error()` is not well-formed, or if its result is not convertible to `bool`, the program is ill-formed. These functions are not visible to ordinary [unqualified](../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../language/adl "cpp/language/adl") when `std::expected<T, E>` is an associated class of the arguments. The `!=` operator is [synthesized](../../language/operators#Relational_operators "cpp/language/operators") from `operator==`. ### Parameters | | | | | --- | --- | --- | | lhs, rhs, x | - | `expected` object to compare | | val | - | value to compare to the expected value contained in `x` | | e | - | value to compare to the unexpected value contained in `x` | ### Return value 1) If `lhs.has_value() != rhs.has_value()`, returns `false`. Otherwise, if `x.has_value()` is true, returns `*lhs == *rhs`. Otherwise, returns `lhs.error() == rhs.error()`. 2) If `lhs.has_value() != rhs.has_value()`, returns `false`. Otherwise, if `x.has_value()` is true, returns `true`. Otherwise, returns `lhs.error() == rhs.error()`. 3) Returns `x.has_value() && static_cast<bool>(*x == val)`. 4) Returns `!x.has_value() && static_cast<bool>(x.error() == e.error())`. ### Exceptions Throws when and what the comparison throws. ### Example ### See also | | | | --- | --- | | [unexpected](unexpected "cpp/utility/expected/unexpected") (C++23) | represented as an unexpected value in expected (class template) | cpp std::expected<T,E>::error std::expected<T,E>::error ========================= | | | | | --- | --- | --- | | ``` constexpr const E& error() const& noexcept; ``` | (1) | (since C++23) | | ``` constexpr E& error() & noexcept; ``` | (2) | (since C++23) | | ``` constexpr const E&& error() const&& noexcept; ``` | (3) | (since C++23) | | ``` constexpr E&& error() && noexcept; ``` | (4) | (since C++23) | Accesses the unexpected value contained in `*this`. The behavior is undefined if [`this->has_value()`](operator_bool "cpp/utility/expected/operator bool") is true. ### Parameters (none). ### Return value Reference to the unexpected value contained in `*this`. ### Example ### See also | | | | --- | --- | | [operator->operator\*](operator* "cpp/utility/expected/operator*") | accesses the expected value (public member function) | | [value](value "cpp/utility/expected/value") | returns the expected value (public member function) | | [operator boolhas\_value](operator_bool "cpp/utility/expected/operator bool") | checks whether the object contains an expected value (public member function) | cpp std::expected<T,E>::value_or std::expected<T,E>::value\_or ============================= | | | | | --- | --- | --- | | ``` template< class U > constexpr T value_or( U&& default_value ) const&; ``` | (1) | (since C++23) | | ``` template< class U > constexpr T value_or( U&& default_value ) &&; ``` | (2) | (since C++23) | Returns the contained value if `*this` contains an expected value, otherwise returns `default_value`. 1) Returns `bool(\*this) ? \*\*this : static\_cast<T>([std::forward](http://en.cppreference.com/w/cpp/utility/forward)<U>(default_value))` 2) Returns `bool(\*this) ? std::move(\*\*this) : static\_cast<T>([std::forward](http://en.cppreference.com/w/cpp/utility/forward)<U>(default_value))` ### Parameters | | | | | --- | --- | --- | | default\_value | - | the value to use in case `*this` is empty | | Type requirements | | -`T` must meet the requirements of [CopyConstructible](../../named_req/copyconstructible "cpp/named req/CopyConstructible") in order to use overload (1). | | -`T` must meet the requirements of [MoveConstructible](../../named_req/moveconstructible "cpp/named req/MoveConstructible") in order to use overload (2). | | -`U&&` must be convertible to `T` | ### Return value The currently contained value if `*this` contains an expected value, or `default_value` otherwise. ### Exceptions Any exception thrown by the selected constructor of the return value `T`. ### Notes If `T` is (possibly cv-qualified) `void`, this member is not declared. ### Example ### See also | | | | --- | --- | | [value](value "cpp/utility/expected/value") | returns the expected value (public member function) | cpp std::optional<T>::reset std::optional<T>::reset ======================= | | | | | --- | --- | --- | | ``` void reset() noexcept; ``` | | (since C++17) (until C++20) | | ``` constexpr void reset() noexcept; ``` | | (since C++20) | If `*this` contains a value, destroy that value as if by `value().T::~T()`. Otherwise, there are no effects. `*this` does not contain a value after this call. ### Example ``` #include <optional> #include <iostream> struct A { std::string s; A(std::string str) : s(std::move(str)) { std::cout << " constructed\n"; } ~A() { std::cout << " destructed\n"; } A(const A& o) : s(o.s) { std::cout << " copy constructed\n"; } A(A&& o) : s(std::move(o.s)) { std::cout << " move constructed\n"; } A& operator=(const A& other) { s = other.s; std::cout << " copy assigned\n"; return *this; } A& operator=(A&& other) { s = std::move(other.s); std::cout << " move assigned\n"; return *this; } }; int main() { std::cout << "Create empty optional:\n"; std::optional<A> opt; std::cout << "Construct and assign value:\n"; opt = A("Lorem ipsum dolor sit amet, consectetur adipiscing elit nec."); std::cout << "Reset optional:\n"; opt.reset(); std::cout << "End example\n"; } ``` Output: ``` Create empty optional: Construct and assign value: constructed move constructed destructed Reset optional: destructed End example ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [P2231R1](https://wg21.link/P2231R1) | C++20 | `reset` was not constexpr while non-trivial destruction is allowed in constexpr in C++20 | made constexpr | ### See also | | | | --- | --- | | [operator=](operator= "cpp/utility/optional/operator=") | assigns contents (public member function) | cpp std::bad_optional_access std::bad\_optional\_access ========================== | Defined in header `[<optional>](../../header/optional "cpp/header/optional")` | | | | --- | --- | --- | | ``` class bad_optional_access; ``` | | (since C++17) | Defines a type of object to be thrown by `[std::optional::value](value "cpp/utility/optional/value")` when accessing an optional object that does not contain a value. ![std-bad optional access-inheritance-lwg2806.svg]() Inheritance diagram. ### Member functions | | | | --- | --- | | (constructor) | constructs a new `bad_optional_access` object (public member function) | | operator= | replaces the `bad_optional_access` object (public member function) | | what | returns the explanatory string (public member function) | std::bad\_optional\_access::bad\_optional\_access -------------------------------------------------- | | | | | --- | --- | --- | | ``` bad_optional_access() noexcept; ``` | (1) | (since C++17) | | ``` bad_optional_access( const bad_optional_access& other ) noexcept; ``` | (2) | (since C++17) | Constructs a new `bad_optional_access` object with an implementation-defined null-terminated byte string which is accessible through [`what()`](../../error/exception/what "cpp/error/exception/what"). 1) Default constructor. 2) Copy constructor. If `*this` and `other` both have dynamic type `std::bad_optional_access` then `[std::strcmp](http://en.cppreference.com/w/cpp/string/byte/strcmp)(what(), other.what()) == 0`. ### Parameters | | | | | --- | --- | --- | | other | - | another exception object to copy | std::bad\_optional\_access::operator= -------------------------------------- | | | | | --- | --- | --- | | ``` bad_optional_access& operator=( const bad_optional_access& other ) noexcept; ``` | | (since C++17) | Assigns the contents with those of `other`. If `*this` and `other` both have dynamic type `std::bad_optional_access` then `[std::strcmp](http://en.cppreference.com/w/cpp/string/byte/strcmp)(what(), other.what()) == 0` after assignment. ### Parameters | | | | | --- | --- | --- | | other | - | another exception object to assign with | ### Return value `*this`. std::bad\_optional\_access::what --------------------------------- | | | | | --- | --- | --- | | ``` virtual const char* what() const noexcept; ``` | | (since C++17) | Returns the explanatory string. ### Parameters (none). ### Return value Pointer to a null-terminated string with explanatory information. The string is suitable for conversion and display as a `[std::wstring](../../string/basic_string "cpp/string/basic string")`. The pointer is guaranteed to be valid at least until the exception object from which it is obtained is destroyed, or until a non-const member function (e.g. copy assignment operator) on the exception object is called. ### Notes Implementations are allowed but not required to override `what()`. Inherited from [std::exception](../../error/exception "cpp/error/exception") ------------------------------------------------------------------------------ ### Member functions | | | | --- | --- | | [(destructor)](../../error/exception/~exception "cpp/error/exception/~exception") [virtual] | destroys the exception object (virtual public member function of `std::exception`) | | [what](../../error/exception/what "cpp/error/exception/what") [virtual] | returns an explanatory string (virtual public member function of `std::exception`) | cpp deduction guides for std::optional deduction guides for `std::optional` ==================================== | Defined in header `[<optional>](../../header/optional "cpp/header/optional")` | | | | --- | --- | --- | | ``` template<class T> optional(T) -> optional<T>; ``` | | (since C++17) | One [deduction guide](../../language/class_template_argument_deduction "cpp/language/class template argument deduction") is provided for `[std::optional](../optional "cpp/utility/optional")` to account for the edge cases missed by the implicit deduction guides, in particular, non-copyable arguments and array to pointer conversion. ### Example ``` #include <optional> int main() { int a[2]; std::optional oa{a}; // explicit deduction guide is used in this case } ``` cpp std::optional<T>::emplace std::optional<T>::emplace ========================= | | | | | --- | --- | --- | | | (1) | | | ``` template< class... Args > T& emplace( Args&&... args ); ``` | (since C++17) (until C++20) | | ``` template< class... Args > constexpr T& emplace( Args&&... args ); ``` | (since C++20) | | | (2) | | | ``` template< class U, class... Args > T& emplace( std::initializer_list<U> ilist, Args&&... args ); ``` | (since C++17) (until C++20) | | ``` template< class U, class... Args > constexpr T& emplace( std::initializer_list<U> ilist, Args&&... args ); ``` | (since C++20) | Constructs the contained value in-place. If `*this` already contains a value before the call, the contained value is destroyed by calling its destructor. 1) Initializes the contained value by [direct-initializing](../../language/direct_initialization "cpp/language/direct initialization") (but not direct-list-initializing) with `[std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Args>(args)...` as parameters. 2) Initializes the contained value by calling its constructor with `ilist, [std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Args>(args)...` as parameters. This overload participates in overload resolution only if `[std::is\_constructible](http://en.cppreference.com/w/cpp/types/is_constructible)<T, [std::initializer\_list](http://en.cppreference.com/w/cpp/utility/initializer_list)<U>&, Args&&...>::value` is `true`. ### Parameters | | | | | --- | --- | --- | | args... | - | the arguments to pass to the constructor | | ilist | - | the initializer list to pass to the constructor | | Type requirements | | -`T` must be constructible from `Args...` for overload (1) | | -`T` must be constructible from `[std::initializer\_list](../initializer_list "cpp/utility/initializer list")` and `Args...` for overload (2) | ### Return value A reference to the new contained value. ### Exceptions Any exception thrown by the selected constructor of `T`. If an exception is thrown, `*this` does not contain a value after this call (the previously contained value, if any, had been destroyed). ### Example ``` #include <optional> #include <iostream> struct A { std::string s; A(std::string str) : s(std::move(str)), id{n++} { note("+ constructed"); } ~A() { note("~ destructed"); } A(const A& o) : s(o.s), id{n++} { note("+ copy constructed"); } A(A&& o) : s(std::move(o.s)), id{n++} { note("+ move constructed"); } A& operator=(const A& other) { s = other.s; note("= copy assigned"); return *this; } A& operator=(A&& other) { s = std::move(other.s); note("= move assigned"); return *this; } inline static int n{}; int id{}; void note(auto s) { std::cout << " " << s << " #" << id << '\n'; } }; int main() { std::optional<A> opt; std::cout << "Assign:\n"; opt = A("Lorem ipsum dolor sit amet, consectetur adipiscing elit nec."); std::cout << "Emplace:\n"; // As opt contains a value it will also destroy that value opt.emplace("Lorem ipsum dolor sit amet, consectetur efficitur."); std::cout << "End example\n"; } ``` Output: ``` Assign: + constructed #0 + move constructed #1 ~ destructed #0 Emplace: ~ destructed #1 + constructed #2 End example ~ destructed #2 ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [P2231R1](https://wg21.link/P2231R1) | C++20 | `emplace` was not constexpr while the required operations can be constexpr in C++20 | made constexpr | ### See also | | | | --- | --- | | [operator=](operator= "cpp/utility/optional/operator=") | assigns contents (public member function) | cpp std::nullopt std::nullopt ============ | Defined in header `[<optional>](../../header/optional "cpp/header/optional")` | | | | --- | --- | --- | | ``` inline constexpr nullopt_t nullopt{/*unspecified*/}; ``` | | (since C++17) | `std::nullopt` is a constant of type `[std::nullopt\_t](nullopt_t "cpp/utility/optional/nullopt t")` that is used to indicate `optional` type with uninitialized state. ### See also | | | | --- | --- | | [nullopt\_t](nullopt_t "cpp/utility/optional/nullopt t") (C++17) | indicator of optional type with uninitialized state (class) | cpp std::optional<T>::transform std::optional<T>::transform =========================== | | | | | --- | --- | --- | | ``` template< class F > constexpr auto transform( F&& f ) &; ``` | (1) | (since C++23) | | ``` template< class F > constexpr auto transform( F&& f ) const&; ``` | (2) | (since C++23) | | ``` template< class F > constexpr auto transform( F&& f ) &&; ``` | (3) | (since C++23) | | ``` template< class F > constexpr auto transform( F&& f ) const&&; ``` | (4) | (since C++23) | Returns an `[std::optional](../optional "cpp/utility/optional")` that contains the result of invocation of `f` on the contained value if `*this` contains a value. Otherwise, returns an empty `[std::optional](../optional "cpp/utility/optional")` of such type. The type of contained value in the result (denoted by `U` below) must be a non-array object type, and must not be `[std::in\_place\_t](../in_place "cpp/utility/in place")` or `[std::nullopt\_t](nullopt_t "cpp/utility/optional/nullopt t")`. Otherwise, the program is ill-formed. 1) Let `U` be `[std::remove\_cv\_t](http://en.cppreference.com/w/cpp/types/remove_cv)<[std::invoke\_result\_t](http://en.cppreference.com/w/cpp/types/result_of)<F, T&>>`. If `*this` contains a value, returns a `[std::optional](http://en.cppreference.com/w/cpp/utility/optional)<U>` whose contained value is directly-non-list-initialized from `[std::invoke](http://en.cppreference.com/w/cpp/utility/functional/invoke)([std::forward](http://en.cppreference.com/w/cpp/utility/forward)<F>(f), this->value())`. Otherwise, returns an empty `[std::optional](http://en.cppreference.com/w/cpp/utility/optional)<U>`. The program is ill-formed if the variable definition `U x([std::invoke](http://en.cppreference.com/w/cpp/utility/functional/invoke)([std::forward](http://en.cppreference.com/w/cpp/utility/forward)<F>(f), this->value()));` is ill-formed. 2) Same as (1), except that `U` is `[std::remove\_cv\_t](http://en.cppreference.com/w/cpp/types/remove_cv)<[std::invoke\_result\_t](http://en.cppreference.com/w/cpp/types/result_of)<F, const T&>>`. 3) Let `U` be `[std::remove\_cv\_t](http://en.cppreference.com/w/cpp/types/remove_cv)<[std::invoke\_result\_t](http://en.cppreference.com/w/cpp/types/result_of)<F, T>>`. If `*this` contains a value, returns a `[std::optional](http://en.cppreference.com/w/cpp/utility/optional)<U>` whose contained value is directly-non-list-initialized from `[std::invoke](http://en.cppreference.com/w/cpp/utility/functional/invoke)([std::forward](http://en.cppreference.com/w/cpp/utility/forward)<F>(f), std::move(this->value()))`. Otherwise, returns an empty `[std::optional](http://en.cppreference.com/w/cpp/utility/optional)<U>`. The program is ill-formed if the variable definition `U x([std::invoke](http://en.cppreference.com/w/cpp/utility/functional/invoke)([std::forward](http://en.cppreference.com/w/cpp/utility/forward)<F>(f), std::move(this->value())));` is ill-formed. 4) Same as (3), except that `U` is `[std::remove\_cv\_t](http://en.cppreference.com/w/cpp/types/remove_cv)<[std::invoke\_result\_t](http://en.cppreference.com/w/cpp/types/result_of)<F, const T>>`. ### Parameters | | | | | --- | --- | --- | | f | - | a suitable function or [Callable](../../named_req/callable "cpp/named req/Callable") object whose call signature returns a non-reference type | ### Return value An `[std::optional](../optional "cpp/utility/optional")` containing the result of `f` or an empty `[std::optional](../optional "cpp/utility/optional")`, as described above. ### Notes Because `transform` directly constructs a `U` object at the right location, rather than passing it to a constructor, `[std::is\_move\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_move_constructible)<U>` can be `false`. As the callable `f` can't return a reference type, it cannot be a [pointer to data member](../../language/pointer#Pointers_to_data_members "cpp/language/pointer"). Some languages call this operation *map*. | [Feature-test](../feature_test "cpp/utility/feature test") macro | Value | Std | | --- | --- | --- | | [`__cpp_lib_optional`](../../feature_test#Library_features "cpp/feature test") | `202110L` | (C++23) | ### Example ``` #include <iostream> #include <optional> struct A { friend std::ostream& operator<< (std::ostream& os, A) { return os << 'A'; } }; struct B { friend std::ostream& operator<< (std::ostream& os, B) { return os << 'B'; } }; struct C { friend std::ostream& operator<< (std::ostream& os, C) { return os << 'C'; } }; struct D { friend std::ostream& operator<< (std::ostream& os, D) { return os << 'D'; } }; auto A_to_B(A in) { B out; std::cout << in << " => " << out << '\n'; return out; } auto B_to_C(B in) { C out; std::cout << in << " => " << out << '\n'; return out; } auto C_to_D(C in) { D out; std::cout << in << " => " << out << '\n'; return out; } int main() { for (std::optional<A> o_A : { std::optional<A>{ A{} }, std::optional<A>{/*empty*/} }) { std::cout << (o_A ? "o_A has a value\n" : "o_A is empty\n"); std::optional<D> o_D = o_A.transform(A_to_B) .transform(B_to_C) .transform(C_to_D); std::cout << (o_D ? "o_D has a value\n\n" : "o_D is empty\n\n"); } } ``` Output: ``` o_A has a value A => B B => C C => D o_D has a value o_A is empty o_D is empty ``` ### See also | | | | --- | --- | | [value\_or](value_or "cpp/utility/optional/value or") | returns the contained value if available, another value otherwise (public member function) | | [and\_then](and_then "cpp/utility/optional/and then") (C++23) | returns the result of the given function on the contained value if it exists, or an empty `optional` otherwise (public member function) | | [or\_else](or_else "cpp/utility/optional/or else") (C++23) | returns the `optional` itself if it contains a value, or the result of the given function otherwise (public member function) |
programming_docs
cpp std::optional<T>::optional std::optional<T>::optional ========================== | | | | | --- | --- | --- | | ``` constexpr optional() noexcept; constexpr optional( std::nullopt_t ) noexcept; ``` | (1) | (since C++17) | | ``` constexpr optional( const optional& other ); ``` | (2) | (since C++17) | | ``` constexpr optional( optional&& other ) noexcept(/* see below */); ``` | (3) | (since C++17) | | | (4) | | | ``` template < class U > optional( const optional<U>& other ); ``` | (since C++17) (until C++20) (conditionally explicit) | | ``` template < class U > constexpr optional( const optional<U>& other ); ``` | (since C++20) (conditionally explicit) | | | (5) | | | ``` template < class U > optional( optional<U>&& other ); ``` | (since C++17) (until C++20) (conditionally explicit) | | ``` template < class U > constexpr optional( optional<U>&& other ); ``` | (since C++20) (conditionally explicit) | | ``` template< class... Args > constexpr explicit optional( std::in_place_t, Args&&... args ); ``` | (6) | (since C++17) | | ``` template< class U, class... Args > constexpr explicit optional( std::in_place_t, std::initializer_list<U> ilist, Args&&... args ); ``` | (7) | (since C++17) | | ``` template < class U = T > constexpr optional( U&& value ); ``` | (8) | (since C++17) (conditionally explicit) | Constructs a new `optional` object. 1) Constructs an object that *does not contain a value*. 2) Copy constructor: If `other` contains a value, initializes the contained value as if [direct-initializing](../../language/direct_initialization "cpp/language/direct initialization") (but not direct-list-initializing) an object of type `T` with the expression `*other`. If `other` does not contain a value, constructs an object that *does not contain a value*. * This constructor is defined as deleted if `[std::is\_copy\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_copy_constructible)<T>` is `false`. * It is a trivial constructor if `[std::is\_trivially\_copy\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_copy_constructible)<T>` is `true`. 3) Move constructor: If `other` contains a value, initializes the contained value as if [direct-initializing](../../language/direct_initialization "cpp/language/direct initialization") (but not direct-list-initializing) an object of type `T` with the expression `std::move(*other)` and *does not* make `other` empty: a moved-from optional still *contains a value*, but the value itself is moved from. If `other` does not contain a value, constructs an object that *does not contain a value*. * This constructor does not participate in overload resolution unless `[std::is\_move\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_move_constructible)<T>` is `true`. * It is a trivial constructor if `[std::is\_trivially\_move\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_move_constructible)<T>` is `true`. 4) Converting copy constructor: If `other` doesn't contain a value, constructs an optional object that does not contain a value. Otherwise, constructs an optional object that contains a value, initialized as if [direct-initializing](../../language/direct_initialization "cpp/language/direct initialization") (but not direct-list-initializing) an object of type `T` with the expression `*other`. * This constructor does not participate in overload resolution unless the following conditions are met: + `[std::is\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_constructible)<T, const U&>` is `true`. + `T` is not constructible or convertible from any expression of type (possibly `const`) `[std::optional](http://en.cppreference.com/w/cpp/utility/optional)<U>`, i.e., the following 8 type traits are all `false`: - `[std::is\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_constructible)<T, [std::optional](http://en.cppreference.com/w/cpp/utility/optional)<U>&>` - `[std::is\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_constructible)<T, const [std::optional](http://en.cppreference.com/w/cpp/utility/optional)<U>&>` - `[std::is\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_constructible)<T, [std::optional](http://en.cppreference.com/w/cpp/utility/optional)<U>&&>` - `[std::is\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_constructible)<T, const [std::optional](http://en.cppreference.com/w/cpp/utility/optional)<U>&&>` - `[std::is\_convertible\_v](http://en.cppreference.com/w/cpp/types/is_convertible)<[std::optional](http://en.cppreference.com/w/cpp/utility/optional)<U>&, T>` - `[std::is\_convertible\_v](http://en.cppreference.com/w/cpp/types/is_convertible)<const [std::optional](http://en.cppreference.com/w/cpp/utility/optional)<U>&, T>` - `[std::is\_convertible\_v](http://en.cppreference.com/w/cpp/types/is_convertible)<[std::optional](http://en.cppreference.com/w/cpp/utility/optional)<U>&&, T>` - `[std::is\_convertible\_v](http://en.cppreference.com/w/cpp/types/is_convertible)<const [std::optional](http://en.cppreference.com/w/cpp/utility/optional)<U>&&, T>` * This constructor is `explicit` if and only if `[std::is\_convertible\_v](http://en.cppreference.com/w/cpp/types/is_convertible)<const U&, T>` is `false`. 5) Converting move constructor: If `other` doesn't contain a value, constructs an optional object that does not contain a value. Otherwise, constructs an optional object that contains a value, initialized as if [direct-initializing](../../language/direct_initialization "cpp/language/direct initialization") (but not direct-list-initializing) an object of type `T` with the expression `std::move(*other)`. * This constructor does not participate in overload resolution unless the following conditions are met: + `[std::is\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_constructible)<T, U&&>` is `true`. + `T` is not constructible or convertible from any expression of type (possibly `const`) `[std::optional](http://en.cppreference.com/w/cpp/utility/optional)<U>`, i.e., the following 8 type traits are all `false`: - `[std::is\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_constructible)<T, [std::optional](http://en.cppreference.com/w/cpp/utility/optional)<U>&>` - `[std::is\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_constructible)<T, const [std::optional](http://en.cppreference.com/w/cpp/utility/optional)<U>&>` - `[std::is\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_constructible)<T, [std::optional](http://en.cppreference.com/w/cpp/utility/optional)<U>&&>` - `[std::is\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_constructible)<T, const [std::optional](http://en.cppreference.com/w/cpp/utility/optional)<U>&&>` - `[std::is\_convertible\_v](http://en.cppreference.com/w/cpp/types/is_convertible)<[std::optional](http://en.cppreference.com/w/cpp/utility/optional)<U>&, T>` - `[std::is\_convertible\_v](http://en.cppreference.com/w/cpp/types/is_convertible)<const [std::optional](http://en.cppreference.com/w/cpp/utility/optional)<U>&, T>` - `[std::is\_convertible\_v](http://en.cppreference.com/w/cpp/types/is_convertible)<[std::optional](http://en.cppreference.com/w/cpp/utility/optional)<U>&&, T>` - `[std::is\_convertible\_v](http://en.cppreference.com/w/cpp/types/is_convertible)<const [std::optional](http://en.cppreference.com/w/cpp/utility/optional)<U>&&, T>` * This constructor is `explicit` if and only if `[std::is\_convertible\_v](http://en.cppreference.com/w/cpp/types/is_convertible)<U&&, T>` is `false`. 6) Constructs an optional object that *contains a value*, initialized as if [direct-initializing](../../language/direct_initialization "cpp/language/direct initialization") (but not direct-list-initializing) an object of type `T` from the arguments `[std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Args>(args)...`. * If the selected constructor of `T` is a `constexpr` constructor, this constructor is a `constexpr` constructor. * The function does not participate in the overload resolution unless `[std::is\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_constructible)<T, Args...>` is `true` 7) Constructs an optional object that *contains a value*, initialized as if [direct-initializing](../../language/direct_initialization "cpp/language/direct initialization") (but not direct-list-initializing) an object of type `T` from the arguments `ilist, [std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Args>(args)...`. * If the selected constructor of `T` is a `constexpr` constructor, this constructor is a `constexpr` constructor. * The function does not participate in the overload resolution unless `[std::is\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_constructible)<T, [std::initializer\_list](http://en.cppreference.com/w/cpp/utility/initializer_list)<U>&, Args&&...>` is `true` 8) Constructs an optional object that *contains a value*, initialized as if [direct-initializing](../../language/direct_initialization "cpp/language/direct initialization") (but not direct-list-initializing) an object of type `T` with the expression `[std::forward](http://en.cppreference.com/w/cpp/utility/forward)<U>(value)`. * If the selected constructor of `T` is a `constexpr` constructor, this constructor is a `constexpr` constructor. * This constructor does not participate in overload resolution unless `[std::is\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_constructible)<T, U&&>` is `true` and `[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<U>` (until C++20)`[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<U>` (since C++20) is neither `[std::in\_place\_t](../in_place "cpp/utility/in place")` nor `[std::optional](http://en.cppreference.com/w/cpp/utility/optional)<T>`. * This constructor is `explicit` if and only if `[std::is\_convertible\_v](http://en.cppreference.com/w/cpp/types/is_convertible)<U&&, T>` is `false`. ### Parameters | | | | | --- | --- | --- | | other | - | another `optional` object whose contained value is copied | | value | - | value with which to initialize the contained value | | args... | - | arguments with which to initialize the contained value | | ilist | - | initializer list with which to initialize the contained value | ### Exceptions 2) Throws any exception thrown by the constructor of `T`. 3) Throws any exception thrown by the constructor of `T`. Has the following [`noexcept`](../../language/noexcept_spec "cpp/language/noexcept spec") specification: `noexcept([std::is\_nothrow\_move\_constructible](http://en.cppreference.com/w/cpp/types/is_move_constructible)<T>::value)` . 4-8) Throws any exception thrown by the constructor of `T`. ### [Deduction guides](deduction_guides "cpp/utility/optional/deduction guides") ### Example ``` #include <optional> #include <iostream> #include <string> int main() { std::optional<int> o1, // empty o2 = 1, // init from rvalue o3 = o2; // copy-constructor // calls std::string( initializer_list<CharT> ) constructor std::optional<std::string> o4(std::in_place, {'a', 'b', 'c'}); // calls std::string( size_type count, CharT ch ) constructor std::optional<std::string> o5(std::in_place, 3, 'A'); // Move-constructed from std::string using deduction guide to pick the type std::optional o6(std::string{"deduction"}); std::cout << *o2 << ' ' << *o3 << ' ' << *o4 << ' ' << *o5 << ' ' << *o6 << '\n'; } ``` Output: ``` 1 1 abc AAA deduction ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [P0602R4](https://wg21.link/P0602R4) | C++17 | copy/move constructors may not be trivial even if underlying constructor is trivial | required to propagate triviality | | [P2231R1](https://wg21.link/P2231R1) | C++20 | converting constructors from another `optional` was not constexprwhile the required operations can be in C++20 | made constexpr | ### See also | | | | --- | --- | | [make\_optional](make_optional "cpp/utility/optional/make optional") (C++17) | creates an `optional` object (function template) | cpp std::hash <std::optional> std::hash <std::optional> ========================= | Defined in header `[<optional>](../../header/optional "cpp/header/optional")` | | | | --- | --- | --- | | ``` template<class T> struct hash<std::optional<T>>; ``` | | (since C++17) | The template specialization of `[std::hash](../hash "cpp/utility/hash")` for the `[std::optional](../optional "cpp/utility/optional")` class allows users to obtain hashes of the values contained in `optional` objects. The specialization `std::hash<optional<T>>` is enabled (see `[std::hash](../hash "cpp/utility/hash")`) if `std::hash<std::remove_const_t<T>>` is enabled, and is disabled otherwise. When enabled, for an object `o` of type `std::optional<T>` that contains a value, `std::hash<std::optional<T>>()(o)` evaluates to the same value as `std::hash<std::remove_const_t<T>>()(*o)`. For an optional that does not contain a value, the hash is unspecified. The member functions of this specialization are not guaranteed to be noexcept because the hash of the underlying type might throw. ### Template parameters | | | | | --- | --- | --- | | T | - | the type of the value contained in `optional` object | ### Example ``` #include <optional> #include <unordered_set> #include <string> #include <iostream> using namespace std::literals; int main() { using OptStr = std::optional<std::string>; // hash<optional> makes it possible to use unordered_set std::unordered_set<OptStr> s = { "ABC"s, "abc"s, std::nullopt, "def"s }; for(const auto& o : s) { std::cout << o.value_or("(null)") << '\t' << std::hash<OptStr>{}(o) << '\n'; } } ``` Possible output: ``` def 11697390762615875584 (null) 18446744073709548283 abc 3663726644998027833 ABC 11746482041453314842 ``` ### See also | | | | --- | --- | | [hash](../hash "cpp/utility/hash") (C++11) | hash function object (class template) | cpp std::optional<T>::swap std::optional<T>::swap ====================== | | | | | --- | --- | --- | | ``` void swap( optional& other ) noexcept(/* see below */); ``` | | (since C++17) (until C++20) | | ``` constexpr void swap( optional& other ) noexcept(/* see below */); ``` | | (since C++20) | Swaps the contents with those of `other`. * If neither `*this` nor `other` contain a value, the function has no effect. * If only one of `*this` and `other` contains a value (let's call this object `in` and the other `un`), the contained value of `un` is [direct-initialized](../../language/direct_initialization "cpp/language/direct initialization") from `std::move(*in)`, followed by destruction of the contained value of `in` as if by `in->T::~T()`. After this call, `in` does not contain a value; `un` contains a value. * If both `*this` and `other` contain values, the contained values are exchanged by calling `using [std::swap](http://en.cppreference.com/w/cpp/algorithm/swap); swap(\*\*this, \*other)`. `T` lvalues must satisfy [Swappable](../../named_req/swappable "cpp/named req/Swappable"). The program is ill-formed if `[std::is\_move\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_move_constructible)<T>` is `false`. ### Parameters | | | | | --- | --- | --- | | other | - | the `optional` object to exchange the contents with | ### Return value (none). ### Exceptions [`noexcept`](../../language/noexcept_spec "cpp/language/noexcept spec") specification: `noexcept([std::is\_nothrow\_move\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_move_constructible)<T> && [std::is\_nothrow\_swappable\_v](http://en.cppreference.com/w/cpp/types/is_swappable)<T>)` In the case of thrown exception, the states of the contained values of `*this` and `other` are determined by the exception safety guarantees of `swap` of type `T` or `T`'s move constructor, whichever is called. For both `*this` and `other`, if the object contained a value, it is left containing a value, and the other way round. ### Example ``` #include <iostream> #include <string> #include <optional> int main() { std::optional<std::string> opt1("First example text"); std::optional<std::string> opt2("2nd text"); enum Swap { Before, After }; auto print_opts = [&](Swap e) { std::cout << (e == Before ? "Before swap:\n" : "After swap:\n"); std::cout << "opt1 contains '" << opt1.value_or("") << "'\n"; std::cout << "opt2 contains '" << opt2.value_or("") << "'\n"; std::cout << (e == Before ? "---SWAP---\n": "\n"); }; print_opts(Before); opt1.swap(opt2); print_opts(After); // Swap with only 1 set opt1 = "Lorem ipsum dolor sit amet, consectetur tincidunt."; opt2.reset(); print_opts(Before); opt1.swap(opt2); print_opts(After); } ``` Output: ``` Before swap: opt1 contains 'First example text' opt2 contains '2nd text' ---SWAP--- After swap: opt1 contains '2nd text' opt2 contains 'First example text' Before swap: opt1 contains 'Lorem ipsum dolor sit amet, consectetur tincidunt.' opt2 contains '' ---SWAP--- After swap: opt1 contains '' opt2 contains 'Lorem ipsum dolor sit amet, consectetur tincidunt.' ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [P2231R1](https://wg21.link/P2231R1) | C++20 | `swap` was not constexpr while the required operations can be constexpr in C++20 | made constexpr | ### See also | | | | --- | --- | | [std::swap(std::optional)](swap2 "cpp/utility/optional/swap2") (C++17) | specializes the `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | cpp std::nullopt_t std::nullopt\_t =============== | Defined in header `[<optional>](../../header/optional "cpp/header/optional")` | | | | --- | --- | --- | | ``` struct nullopt_t; ``` | | (since C++17) | `std::nullopt_t` is an empty class type used to indicate `optional` type with uninitialized state. In particular, `[std::optional](http://en.cppreference.com/w/cpp/utility/optional)` has a constructor with `nullopt_t` as a single argument, which creates an optional that does not contain a value. `std::nullopt_t` must be a non-aggregate [LiteralType](../../named_req/literaltype "cpp/named req/LiteralType") and cannot have a default constructor or an initializer-list constructor. It must have a `constexpr` constructor that takes some implementation-defined literal type. ### Notes The constraints on `nullopt_t`'s constructors exist to support both `op = {};` and `op = nullopt;` as the syntax for disengaging an optional object. A possible implementation of this class is. ``` struct nullopt_t { explicit constexpr nullopt_t(int) {} }; ``` ### See also | | | | --- | --- | | [nullopt](nullopt "cpp/utility/optional/nullopt") (C++17) | an object of type `nullopt_t` (constant) | cpp std::make_optional std::make\_optional =================== | Defined in header `[<optional>](../../header/optional "cpp/header/optional")` | | | | --- | --- | --- | | ``` template< class T > constexpr std::optional<std::decay_t<T>> make_optional( T&& value ); ``` | (1) | (since C++17) | | ``` template< class T, class... Args > constexpr std::optional<T> make_optional( Args&&... args ); ``` | (2) | (since C++17) | | ``` template< class T, class U, class... Args > constexpr std::optional<T> make_optional( std::initializer_list<U> il, Args&&... args ); ``` | (3) | (since C++17) | 1) Creates an optional object from `value`. Effectively calls `[std::optional](http://en.cppreference.com/w/cpp/utility/optional)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<T>>([std::forward](http://en.cppreference.com/w/cpp/utility/forward)<T>(value))` 2) Creates an optional object constructed in-place from `args...`. Equivalent to `return [std::optional](http://en.cppreference.com/w/cpp/utility/optional)<T>([std::in\_place](http://en.cppreference.com/w/cpp/utility/in_place), [std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Args>(args)...);`. 3) Creates an optional object constructed in-place from `il` and `args...`. Equivalent to `return [std::optional](http://en.cppreference.com/w/cpp/utility/optional)<T>([std::in\_place](http://en.cppreference.com/w/cpp/utility/in_place), il, [std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Args>(args)...);`. ### Parameters | | | | | --- | --- | --- | | value | - | the value to construct optional object with | | il, args | - | arguments to be passed to the constructor of `T`. | ### Return value The constructed optional object. ### Exceptions Throws any exception thrown by the constructor of `T`. ### Notes `T` need not be movable for overloads (2-3) due to guaranteed copy elision. ### Example ``` #include <optional> #include <iostream> #include <iomanip> #include <vector> #include <string> int main() { auto op1 = std::make_optional<std::vector<char>>({'a','b','c'}); std::cout << "op1: "; for (char c: op1.value()){ std::cout << c << ","; } auto op2 = std::make_optional<std::vector<int>>(5, 2); std::cout << "\nop2: "; for (int i: *op2){ std::cout << i << ","; } std::string str{"hello world"}; auto op3 = std::make_optional<std::string>(std::move(str)); std::cout << "\nop3: " << quoted(op3.value_or("empty value")) << '\n'; std::cout << "str: " << std::quoted(str) << '\n'; } ``` Possible output: ``` op1: a,b,c, op2: 2,2,2,2,2, op3: "hello world" str: "" ``` ### See also | | | | --- | --- | | [(constructor)](optional "cpp/utility/optional/optional") | constructs the optional object (public member function) |
programming_docs
cpp std::optional<T>::operator->, std::optional<T>::operator* std::optional<T>::operator->, std::optional<T>::operator\* ========================================================== | | | | | --- | --- | --- | | ``` constexpr const T* operator->() const noexcept; ``` | (1) | (since C++17) | | ``` constexpr T* operator->() noexcept; ``` | (1) | (since C++17) | | ``` constexpr const T& operator*() const& noexcept; ``` | (2) | (since C++17) | | ``` constexpr T& operator*() & noexcept; ``` | (2) | (since C++17) | | ``` constexpr const T&& operator*() const&& noexcept; ``` | (2) | (since C++17) | | ``` constexpr T&& operator*() && noexcept; ``` | (2) | (since C++17) | Accesses the contained value. 1) Returns a pointer to the contained value. 2) Returns a reference to the contained value. The behavior is undefined if `*this` does not contain a value. ### Parameters (none). ### Return value Pointer or reference to the contained value. ### Notes This operator does not check whether the optional contains a value! You can do so manually by using `[has\_value()](operator_bool "cpp/utility/optional/operator bool")` or simply `[operator bool()](operator_bool "cpp/utility/optional/operator bool")`. Alternatively, if checked access is needed, `[value()](value "cpp/utility/optional/value")` or `[value\_or()](value_or "cpp/utility/optional/value or")` may be used. ### Example ``` #include <optional> #include <iostream> #include <string> int main() { using namespace std::string_literals; std::optional<int> opt1 = 1; std::cout<< "opt1: " << *opt1 << '\n'; *opt1 = 2; std::cout<< "opt1: " << *opt1 << '\n'; std::optional<std::string> opt2 = "abc"s; std::cout<< "opt2: " << *opt2 << " size: " << opt2->size() << '\n'; // You can "take" the contained value by calling operator* on a rvalue to optional auto taken = *std::move(opt2); std::cout << "taken: " << taken << " opt2: " << *opt2 << "size: " << opt2->size() << '\n'; } ``` Output: ``` opt1: 1 opt1: 2 opt2: abc size: 3 taken: abc opt2: size: 0 ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 2762](https://cplusplus.github.io/LWG/issue2762) | C++17 | `operator->` and `operator*` might be potentially-throwing | made noexcept | ### See also | | | | --- | --- | | [value](value "cpp/utility/optional/value") | returns the contained value (public member function) | | [value\_or](value_or "cpp/utility/optional/value or") | returns the contained value if available, another value otherwise (public member function) | cpp std::optional<T>::or_else std::optional<T>::or\_else ========================== | | | | | --- | --- | --- | | ``` template< class F > constexpr optional or_else( F&& f ) const&; ``` | (1) | (since C++23) | | ``` template< class F > constexpr optional or_else( F&& f ) &&; ``` | (2) | (since C++23) | Returns `*this` if it contains a value. Otherwise, returns the result of `f`. The program is ill-formed if `[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<[std::invoke\_result\_t](http://en.cppreference.com/w/cpp/types/result_of)<F>>` is not same as `[std::optional](http://en.cppreference.com/w/cpp/utility/optional)<T>`. 1) Equivalent to `return \*this ? \*this : [std::forward](http://en.cppreference.com/w/cpp/utility/forward)<F>(f)();`. This overload participates in overload resolution only if both `[std::copy\_constructible](http://en.cppreference.com/w/cpp/concepts/copy_constructible)<T>` and `[std::invocable](http://en.cppreference.com/w/cpp/concepts/invocable)<F>` are modeled. 2) Equivalent to `return \*this ? std::move(\*this) : [std::forward](http://en.cppreference.com/w/cpp/utility/forward)<F>(f)();`. This overload participates in overload resolution only if both `[std::move\_constructible](http://en.cppreference.com/w/cpp/concepts/move_constructible)<T>` and `[std::invocable](http://en.cppreference.com/w/cpp/concepts/invocable)<F>` are modeled. ### Parameters | | | | | --- | --- | --- | | f | - | a function or [Callable](../../named_req/callable "cpp/named req/Callable") object that returns an `[std::optional](http://en.cppreference.com/w/cpp/utility/optional)<T>` | ### Return value `*this` or the result of `f`, as described above. ### Notes | [Feature-test](../feature_test "cpp/utility/feature test") macro | Value | Std | | --- | --- | --- | | [`__cpp_lib_optional`](../../feature_test#Library_features "cpp/feature test") | `202110L` | (C++23) | ### Example ### See also | | | | --- | --- | | [value\_or](value_or "cpp/utility/optional/value or") | returns the contained value if available, another value otherwise (public member function) | | [and\_then](and_then "cpp/utility/optional/and then") (C++23) | returns the result of the given function on the contained value if it exists, or an empty `optional` otherwise (public member function) | | [transform](transform "cpp/utility/optional/transform") (C++23) | returns an `optional` containing the transformed contained value if it exists, or an empty `optional` otherwise (public member function) | cpp std::swap(std::optional) std::swap(std::optional) ======================== | Defined in header `[<optional>](../../header/optional "cpp/header/optional")` | | | | --- | --- | --- | | ``` template< class T > void swap( std::optional<T>& lhs, std::optional<T>& rhs ) noexcept(/* see below */); ``` | | (since C++17) (until C++20) | | ``` template< class T > constexpr void swap( std::optional<T>& lhs, std::optional<T>& rhs ) noexcept(/* see below */); ``` | | (since C++20) | Overloads the `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` algorithm for `[std::optional](../optional "cpp/utility/optional")`. Exchanges the state of `lhs` with that of `rhs`. Effectively calls `lhs.swap(rhs)`. This overload participates in overload resolution only if `[std::is\_move\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_move_constructible)<T>` and `[std::is\_swappable\_v](http://en.cppreference.com/w/cpp/types/is_swappable)<T>` are both `true`. ### Parameters | | | | | --- | --- | --- | | lhs, rhs | - | `optional` objects whose states to swap | ### Return value (none). ### Exceptions [`noexcept`](../../language/noexcept_spec "cpp/language/noexcept spec") specification: `noexcept(noexcept(lhs.swap(rhs)))` ### Example ``` #include <iostream> #include <optional> #include <string> int main() { std::optional<std::string> a{"██████"}, b{"▒▒▒▒▒▒"}; auto print = [&](auto const& s) { std::cout << s << "\t" << "a = " << a.value_or("(null)") << " " << "b = " << b.value_or("(null)") << '\n'; }; print("Initially:"); std::swap(a, b); print("swap(a, b):"); a.reset(); print("\n""a.reset():"); std::swap(a, b); print("swap(a, b):"); } ``` Output: ``` Initially: a = ██████ b = ▒▒▒▒▒▒ swap(a, b): a = ▒▒▒▒▒▒ b = ██████ a.reset(): a = (null) b = ██████ swap(a, b): a = ██████ b = (null) ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [P2231R1](https://wg21.link/P2231R1) | C++20 | `swap` was not constexpr while the required operations can be constexpr in C++20 | made constexpr | ### See also | | | | --- | --- | | [swap](swap "cpp/utility/optional/swap") | exchanges the contents (public member function) | cpp std::optional<T>::operator= std::optional<T>::operator= =========================== | | | | | --- | --- | --- | | | (1) | | | ``` optional& operator=( std::nullopt_t ) noexcept; ``` | (since C++17) (until C++20) | | ``` constexpr optional& operator=( std::nullopt_t ) noexcept; ``` | (since C++20) | | ``` constexpr optional& operator=( const optional& other ); ``` | (2) | (since C++17) | | ``` constexpr optional& operator=( optional&& other ) noexcept(/* see below */); ``` | (3) | (since C++17) | | | (4) | | | ``` template< class U = T > optional& operator=( U&& value ); ``` | (since C++17) (until C++20) | | ``` template< class U = T > constexpr optional& operator=( U&& value ); ``` | (since C++20) | | | (5) | | | ``` template< class U > optional& operator=( const optional<U>& other ); ``` | (since C++17) (until C++20) | | ``` template< class U > constexpr optional& operator=( const optional<U>& other ); ``` | (since C++20) | | | (6) | | | ``` template< class U > optional& operator=( optional<U>&& other ); ``` | (since C++17) (until C++20) | | ``` template< class U > constexpr optional& operator=( optional<U>&& other ); ``` | (since C++20) | Replaces contents of `*this` with the contents of `other`. 1) If `*this` contains a value before the call, the contained value is destroyed by calling its destructor as if by `value().T::~T()`. `*this` does not contain a value after this call. 2-3) Assigns the state of `other`. * If both `*this` and `other` do not contain a value, the function has no effect. * If `*this` contains a value, but `other` does not, then the contained value is destroyed by calling its destructor. `*this` does not contain a value after the call. * If `other` contains a value, then depending on whether `*this` contains a value, the contained value is either [direct-initialized](../../language/direct_initialization "cpp/language/direct initialization") or assigned from `*other` (2) or `std::move(*other)` (3). Note that a moved-from optional still *contains a value*. * Overload (2) is defined as deleted unless `[std::is\_copy\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_copy_constructible)<T>` and `[std::is\_copy\_assignable\_v](http://en.cppreference.com/w/cpp/types/is_copy_assignable)<T>` are both `true`. It is trivial if `[std::is\_trivially\_copy\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_copy_constructible)<T>`, `[std::is\_trivially\_copy\_assignable\_v](http://en.cppreference.com/w/cpp/types/is_copy_assignable)<T>` and `[std::is\_trivially\_destructible\_v](http://en.cppreference.com/w/cpp/types/is_destructible)<T>` are all `true`. * Overload (3) does not participate in overload resolution unless `[std::is\_move\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_move_constructible)<T>` and `[std::is\_move\_assignable\_v](http://en.cppreference.com/w/cpp/types/is_move_assignable)<T>` are both `true`. It is trivial if `[std::is\_trivially\_move\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_move_constructible)<T>`, `[std::is\_trivially\_move\_assignable\_v](http://en.cppreference.com/w/cpp/types/is_move_assignable)<T>` and `[std::is\_trivially\_destructible\_v](http://en.cppreference.com/w/cpp/types/is_destructible)<T>` are all `true`. 4) Perfect-forwarded assignment: depending on whether `*this` contains a value before the call, the contained value is either direct-initialized from `[std::forward](http://en.cppreference.com/w/cpp/utility/forward)<U>(value)` or assigned from `[std::forward](http://en.cppreference.com/w/cpp/utility/forward)<U>(value)`. The function does not participate in overload resolution unless `[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<U>` (until C++20)`[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<U>` (since C++20) is not `[std::optional](http://en.cppreference.com/w/cpp/utility/optional)<T>`, `[std::is\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_constructible)<T, U>` is `true`, `[std::is\_assignable\_v](http://en.cppreference.com/w/cpp/types/is_assignable)<T&, U>` is `true`, and at least one of the following is true: * `T` is not a [scalar type](../../language/type "cpp/language/type"); * `[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<U>` is not `T`. 5-6) Assigns the state of `other`. * If both `*this` and `other` do not contain a value, the function has no effect. * If `*this` contains a value, but `other` does not, then the contained value is destroyed by calling its destructor. `*this` does not contain a value after the call. * If `other` contains a value, then depending on whether `*this` contains a value, the contained value is either [direct-initialized](../../language/direct_initialization "cpp/language/direct initialization") or assigned from `*other` (5) or `std::move(*other)` (6). Note that a moved-from optional still *contains a value*. * These overloads do not participate in overload resolution unless the following conditions are met: + `T` is not constructible, convertible, or assignable from any expression of type (possibly `const`) `[std::optional](http://en.cppreference.com/w/cpp/utility/optional)<U>`, i.e., the following 12 type traits are all `false`: - `[std::is\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_constructible)<T, [std::optional](http://en.cppreference.com/w/cpp/utility/optional)<U>&>` - `[std::is\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_constructible)<T, const [std::optional](http://en.cppreference.com/w/cpp/utility/optional)<U>&>` - `[std::is\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_constructible)<T, [std::optional](http://en.cppreference.com/w/cpp/utility/optional)<U>&&>` - `[std::is\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_constructible)<T, const [std::optional](http://en.cppreference.com/w/cpp/utility/optional)<U>&&>` - `[std::is\_convertible\_v](http://en.cppreference.com/w/cpp/types/is_convertible)<[std::optional](http://en.cppreference.com/w/cpp/utility/optional)<U>&, T>` - `[std::is\_convertible\_v](http://en.cppreference.com/w/cpp/types/is_convertible)<const [std::optional](http://en.cppreference.com/w/cpp/utility/optional)<U>&, T>` - `[std::is\_convertible\_v](http://en.cppreference.com/w/cpp/types/is_convertible)<[std::optional](http://en.cppreference.com/w/cpp/utility/optional)<U>&&, T>` - `[std::is\_convertible\_v](http://en.cppreference.com/w/cpp/types/is_convertible)<const [std::optional](http://en.cppreference.com/w/cpp/utility/optional)<U>&&, T>` - `[std::is\_assignable\_v](http://en.cppreference.com/w/cpp/types/is_assignable)<T&, [std::optional](http://en.cppreference.com/w/cpp/utility/optional)<U>&>` - `[std::is\_assignable\_v](http://en.cppreference.com/w/cpp/types/is_assignable)<T&, const [std::optional](http://en.cppreference.com/w/cpp/utility/optional)<U>&>` - `[std::is\_assignable\_v](http://en.cppreference.com/w/cpp/types/is_assignable)<T&, [std::optional](http://en.cppreference.com/w/cpp/utility/optional)<U>&&>` - `[std::is\_assignable\_v](http://en.cppreference.com/w/cpp/types/is_assignable)<T&, const [std::optional](http://en.cppreference.com/w/cpp/utility/optional)<U>&&>`. + For overload (5), `[std::is\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_constructible)<T, const U&>` and `[std::is\_assignable\_v](http://en.cppreference.com/w/cpp/types/is_assignable)<T&, const U&>` are both `true`. + For overload (6), `[std::is\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_constructible)<T, U>` and `[std::is\_assignable\_v](http://en.cppreference.com/w/cpp/types/is_assignable)<T&, U>` are both `true`. ### Parameters | | | | | --- | --- | --- | | other | - | another `optional` object whose contained value to assign | | value | - | value to assign to the contained value | ### Return value `*this`. ### Exceptions 2-6) Throws any exception thrown by the constructor or assignment operator of `T`. If an exception is thrown, the initialization state of `*this` (and of `other` in case of (2-3) and (5-6) ) is unchanged, i.e. if the object contained a value, it still contains a value, and the other way round. The contents of `value` and the contained values of `*this` and `other` depend on the exception safety guarantees of the operation from which the exception originates (copy-constructor, move-assignment, etc.). (3) has following [`noexcept`](../../language/noexcept_spec "cpp/language/noexcept spec") specification: `noexcept([std::is\_nothrow\_move\_assignable\_v](http://en.cppreference.com/w/cpp/types/is_move_assignable)<T> && [std::is\_nothrow\_move\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_move_constructible)<T>)` ### Notes An optional object `op` may be turned into an empty optional with both `op = {};` and `op = nullopt;`. The first expression constructs an empty `optional` object with `{}` and assigns it to `op`. ### Example ``` #include <optional> #include <iostream> int main() { std::optional<const char*> s1 = "abc", s2; // constructor s2 = s1; // assignment s1 = "def"; // decaying assignment (U = char[4], T = const char*) std::cout << *s2 << ' ' << *s1 << '\n'; } ``` Output: ``` abc def ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [P0602R4](https://wg21.link/P0602R4) | C++17 | copy/move assignment operator may not be trivialeven if underlying operations are trivial | required to propagate triviality | | [P2231R1](https://wg21.link/P2231R1) | C++20 | converting assignment operators were not constexprwhile the required operations can be in C++20 | made constexpr | ### See also | | | | --- | --- | | [emplace](emplace "cpp/utility/optional/emplace") | constructs the contained value in-place (public member function) | cpp std::optional<T>::value std::optional<T>::value ======================= | | | | | --- | --- | --- | | ``` constexpr T& value() &; constexpr const T& value() const &; ``` | (1) | (since C++17) | | ``` constexpr T&& value() &&; constexpr const T&& value() const &&; ``` | (2) | (since C++17) | If `*this` contains a value, returns a reference to the contained value. Otherwise, throws a `[std::bad\_optional\_access](bad_optional_access "cpp/utility/optional/bad optional access")` exception. ### Parameters (none). ### Return value A reference to the contained value. ### Exceptions `[std::bad\_optional\_access](bad_optional_access "cpp/utility/optional/bad optional access")` if `*this` does not contain a value. ### Notes The dereference operator `[operator\*()](operator* "cpp/utility/optional/operator*")` does not check if this optional contains a value, which may be more efficient than `value()`. ### Example ``` #include <optional> #include <iostream> int main() { std::optional<int> opt = {}; try { [[maybe_unused]] int n = opt.value(); } catch(const std::bad_optional_access& e) { std::cout << e.what() << '\n'; } try { opt.value() = 42; } catch(const std::bad_optional_access& e) { std::cout << e.what() << '\n'; } opt = 43; std::cout << *opt << '\n'; opt.value() = 44; std::cout << opt.value() << '\n'; } ``` Output: ``` bad optional access bad optional access 43 44 ``` ### See also | | | | --- | --- | | [value\_or](value_or "cpp/utility/optional/value or") | returns the contained value if available, another value otherwise (public member function) | | [operator->operator\*](operator* "cpp/utility/optional/operator*") | accesses the contained value (public member function) | | [bad\_optional\_access](bad_optional_access "cpp/utility/optional/bad optional access") (C++17) | exception indicating checked access to an optional that doesn't contain a value (class) |
programming_docs
cpp std::optional<T>::~optional std::optional<T>::~optional =========================== | | | | | --- | --- | --- | | ``` ~optional(); ``` | | (since C++17) (until C++20) | | ``` constexpr ~optional(); ``` | | (since C++20) | If the object contains a value and the type `T` is not trivially destructible (see `[std::is\_trivially\_destructible](../../types/is_destructible "cpp/types/is destructible")`), destroys the contained value by calling its destructor, as if by `value().T::~T()`. Otherwise, does nothing. ### Notes If `T` is trivially-destructible, then this destructor is also trivial, so `[std::optional](http://en.cppreference.com/w/cpp/utility/optional)<T>` is also trivially-destructible. ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [P2231R1](https://wg21.link/P2231R1) | C++20 | the destructor was not constexpr while non-trivial destructors can be constexpr in C++20 | made constexpr | cpp std::optional<T>::and_then std::optional<T>::and\_then =========================== | | | | | --- | --- | --- | | ``` template< class F > constexpr auto and_then( F&& f ) &; ``` | (1) | (since C++23) | | ``` template< class F > constexpr auto and_then( F&& f ) const&; ``` | (2) | (since C++23) | | ``` template< class F > constexpr auto and_then( F&& f ) &&; ``` | (3) | (since C++23) | | ``` template< class F > constexpr auto and_then( F&& f ) const&&; ``` | (4) | (since C++23) | Returns the result of invocation of `f` on the contained value if it exists. Otherwise, returns an empty value of the return type. The return type (see below) must be a specialization of `[std::optional](../optional "cpp/utility/optional")`. Otherwise, the program is ill-formed. 1) Equivalent to ``` if (*this) return std::invoke(std::forward<F>(f), this->value()); else return std::remove_cvref_t<std::invoke_result_t<F, T&>>(); ``` 2) Equivalent to ``` if (*this) return std::invoke(std::forward<F>(f), this->value()); else return std::remove_cvref_t<std::invoke_result_t<F, const T&>>(); ``` 3) Equivalent to ``` if (*this) return std::invoke(std::forward<F>(f), std::move(this->value())); else return std::remove_cvref_t<std::invoke_result_t<F, T>>(); ``` 4) Equivalent to ``` if (*this) return std::invoke(std::forward<F>(f), std::move(this->value())); else return std::remove_cvref_t<std::invoke_result_t<F, const T>>(); ``` ### Parameters | | | | | --- | --- | --- | | f | - | a suitable function or [Callable](../../named_req/callable "cpp/named req/Callable") object that returns an `[std::optional](../optional "cpp/utility/optional")` | ### Return value The result of `f` or an empty `[std::optional](../optional "cpp/utility/optional")`, as described above. ### Notes Some languages call this operation *flatmap*. | [Feature-test](../feature_test "cpp/utility/feature test") macro | Value | Std | | --- | --- | --- | | [`__cpp_lib_optional`](../../feature_test#Library_features "cpp/feature test") | `202110L` | (C++23) | ### Example ``` #include <optional> #include <vector> #include <iostream> #include <string> #include <charconv> #include <ranges> std::optional<int> to_int(std::string_view sv) { int r{}; auto [ptr, ec] { std::from_chars(sv.data(), sv.data() + sv.size(), r) }; if (ec == std::errc()) return r; else return std::nullopt; } int main() { using namespace std::literals; std::vector<std::optional<std::string>> v = { "1234", "15 foo", "bar", "42", "5000000000", " 5" }; for( auto&& x : v | std::views::transform([](auto&& o) { return o.and_then(to_int) // flatmap from strings to ints // (making empty optionals where it fails) .transform([](int n) { return n+1; }) // map int to int + 1 .transform([](int n) { return std::to_string(n); }) // convert back to strings .or_else([]{ return std::optional{"Null"s}; // replace all empty optionals // that were left by and_then and // ignored by transforms with "Null" }); }) ) std::cout << *x << '\n'; } ``` Output: ``` 1235 16 Null 43 Null Null ``` ### See also | | | | --- | --- | | [value\_or](value_or "cpp/utility/optional/value or") | returns the contained value if available, another value otherwise (public member function) | | [transform](transform "cpp/utility/optional/transform") (C++23) | returns an `optional` containing the transformed contained value if it exists, or an empty `optional` otherwise (public member function) | | [or\_else](or_else "cpp/utility/optional/or else") (C++23) | returns the `optional` itself if it contains a value, or the result of the given function otherwise (public member function) | cpp operator==, !=, <, <=, >, >=, <=>(std::optional) operator==, !=, <, <=, >, >=, <=>(std::optional) ================================================ | Defined in header `[<optional>](../../header/optional "cpp/header/optional")` | | | | --- | --- | --- | | Compare two `optional` objects | | | | ``` template< class T, class U > constexpr bool operator==( const optional<T>& lhs, const optional<U>& rhs ); ``` | (1) | (since C++17) | | ``` template< class T, class U > constexpr bool operator!=( const optional<T>& lhs, const optional<U>& rhs ); ``` | (2) | (since C++17) | | ``` template< class T, class U > constexpr bool operator<( const optional<T>& lhs, const optional<U>& rhs ); ``` | (3) | (since C++17) | | ``` template< class T, class U > constexpr bool operator<=( const optional<T>& lhs, const optional<U>& rhs ); ``` | (4) | (since C++17) | | ``` template< class T, class U > constexpr bool operator>( const optional<T>& lhs, const optional<U>& rhs ); ``` | (5) | (since C++17) | | ``` template< class T, class U > constexpr bool operator>=( const optional<T>& lhs, const optional<U>& rhs ); ``` | (6) | (since C++17) | | ``` template< class T, std::three_way_comparable_with<T> U > constexpr std::compare_three_way_result_t<T, U> operator<=>( const optional<T>& lhs, const optional<U>& rhs ); ``` | (7) | (since C++20) | | Compare an `optional` object with a `nullopt` | | | | ``` template< class T > constexpr bool operator==( const optional<T>& opt, std::nullopt_t ) noexcept; ``` | (8) | (since C++17) | | ``` template< class T > constexpr bool operator==( std::nullopt_t, const optional<T>& opt ) noexcept; ``` | (9) | (since C++17) (until C++20) | | ``` template< class T > constexpr bool operator!=( const optional<T>& opt, std::nullopt_t ) noexcept; ``` | (10) | (since C++17) (until C++20) | | ``` template< class T > constexpr bool operator!=( std::nullopt_t, const optional<T>& opt ) noexcept; ``` | (11) | (since C++17) (until C++20) | | ``` template< class T > constexpr bool operator<( const optional<T>& opt, std::nullopt_t ) noexcept; ``` | (12) | (since C++17) (until C++20) | | ``` template< class T > constexpr bool operator<( std::nullopt_t, const optional<T>& opt ) noexcept; ``` | (13) | (since C++17) (until C++20) | | ``` template< class T > constexpr bool operator<=( const optional<T>& opt, std::nullopt_t ) noexcept; ``` | (14) | (since C++17) (until C++20) | | ``` template< class T > constexpr bool operator<=( std::nullopt_t, const optional<T>& opt) noexcept; ``` | (15) | (since C++17) (until C++20) | | ``` template< class T > constexpr bool operator>( const optional<T>& opt, std::nullopt_t ) noexcept; ``` | (16) | (since C++17) (until C++20) | | ``` template< class T > constexpr bool operator>( std::nullopt_t, const optional<T>& opt ) noexcept; ``` | (17) | (since C++17) (until C++20) | | ``` template< class T > constexpr bool operator>=( const optional<T>& opt, std::nullopt_t ) noexcept; ``` | (18) | (since C++17) (until C++20) | | ``` template< class T > constexpr bool operator>=( std::nullopt_t, const optional<T>& opt ) noexcept; ``` | (19) | (since C++17) (until C++20) | | ``` template< class T > constexpr std::strong_ordering operator<=>( const optional<T>& opt, std::nullopt_t ) noexcept; ``` | (20) | (since C++20) | | Compare an `optional` object with a value | | | | ``` template< class T, class U > constexpr bool operator==( const optional<T>& opt, const U& value); ``` | (21) | (since C++17) | | ``` template< class T, class U > constexpr bool operator==( const T& value, const optional<U>& opt ); ``` | (22) | (since C++17) | | ``` template< class T, class U > constexpr bool operator!=( const optional<T>& opt, const U& value ); ``` | (23) | (since C++17) | | ``` template< class T, class U > constexpr bool operator!=( const T& value, const optional<U>& opt ); ``` | (24) | (since C++17) | | ``` template< class T, class U > constexpr bool operator<( const optional<T>& opt, const U& value ); ``` | (25) | (since C++17) | | ``` template< class T, class U > constexpr bool operator<( const T& value, const optional<U>& opt ); ``` | (26) | (since C++17) | | ``` template< class T, class U > constexpr bool operator<=( const optional<T>& opt, const U& value ); ``` | (27) | (since C++17) | | ``` template< class T, class U > constexpr bool operator<=( const T& value, const optional<U>& opt); ``` | (28) | (since C++17) | | ``` template< class T, class U > constexpr bool operator>( const optional<T>& opt, const U& value ); ``` | (29) | (since C++17) | | ``` template< class T, class U > constexpr bool operator>( const T& value, const optional<U>& opt ); ``` | (30) | (since C++17) | | ``` template< class T, class U > constexpr bool operator>=( const optional<T>& opt, const U& value ); ``` | (31) | (since C++17) | | ``` template< class T, class U > constexpr bool operator>=( const T& value, const optional<U>& opt ); ``` | (32) | (since C++17) | | ``` template< class T, std::three_way_comparable_with<T> U > constexpr std::compare_three_way_result_t<T, U> operator<=>( const optional<T>& opt, const U& value ); ``` | (33) | (since C++20) | Performs comparison operations on `optional` objects. 1-7) Compares two `optional` objects, `lhs` and `rhs`. The contained values are compared (using the corresponding operator of `T`) only if both `lhs` and `rhs` contain values. Otherwise, * `lhs` is considered *equal to* `rhs` if, and only if, both `lhs` and `rhs` do not contain a value. * `lhs` is considered *less than* `rhs` if, and only if, `rhs` contains a value and `lhs` does not. 8-20) Compares `opt` with a `nullopt`. Equivalent to (1-6) when comparing to an `optional` that does not contain a value. | | | | --- | --- | | The `<`, `<=`, `>`, `>=`, and `!=` operators are [synthesized](../../language/operators#Relational_operators "cpp/language/operators") from `operator<=>` and `operator==` respectively. | (since C++20) | 21-33) Compares `opt` with a `value`. The values are compared (using the corresponding operator of `T`) only if `opt` contains a value. Otherwise, `opt` is considered *less than* `value`. If the corresponding two-way comparison expression between `*opt` and `value` is not well-formed, or if its result is not convertible to `bool`, the program is ill-formed. ### Parameters | | | | | --- | --- | --- | | lhs, rhs, opt | - | an `optional` object to compare | | value | - | value to compare to the contained value | ### Return value 1) If `bool(lhs) != bool(rhs)`, returns `false` Otherwise, if `bool(lhs) == false` (and so `bool(rhs) == false` as well), returns `true` Otherwise, returns `*lhs == *rhs`. 2) If `bool(lhs) != bool(rhs)`, returns `true` Otherwise, if `bool(lhs) == false` (and so `bool(rhs) == false` as well), returns `false` Otherwise, returns `*lhs != *rhs`. 3) If `bool(rhs) == false` returns `false` Otherwise, if `bool(lhs) == false`, returns `true` Otherwise returns `*lhs < *rhs`. 4) If `bool(lhs) == false` returns `true` Otherwise, if `bool(rhs) == false`, returns `false` Otherwise returns `*lhs <= *rhs`. 5) If `bool(lhs) == false` returns `false` Otherwise, if `bool(rhs) == false`, returns `true` Otherwise returns `*lhs > *rhs`. 6) If `bool(rhs) == false` returns `true` Otherwise, if `bool(lhs) == false`, returns `false` Otherwise returns `*lhs >= *rhs`. 7) If `bool(lhs) && bool(rhs)` is `true` returns `*x <=> *y` Otherwise, returns `bool(lhs) <=> bool(rhs)` 8-9) Returns `!opt`. 10-11) Returns `bool(opt)`. 12) Returns `false`. 13) Returns `bool(opt)`. 14) Returns `!opt`. 15) Returns `true`. 16) Returns `bool(opt)`. 17) Returns `false`. 18) Returns `true`. 19) Returns `!opt`. 20) Returns `bool(opt) <=> false`. 21) Returns `bool(opt) ? *opt == value : false`. 22) Returns `bool(opt) ? value == *opt : false`. 23) Returns `bool(opt) ? *opt != value : true`. 24) Returns `bool(opt) ? value != *opt : true`. 25) Returns `bool(opt) ? *opt < value : true`. 26) Returns `bool(opt) ? value < *opt : false`. 27) Returns `bool(opt) ? *opt <= value : true`. 28) Returns `bool(opt) ? value <= *opt : false`. 29) Returns `bool(opt) ? *opt > value : false`. 30) Returns `bool(opt) ? value > *opt : true`. 31) Returns `bool(opt) ? *opt >= value : false`. 32) Returns `bool(opt) ? value >= *opt : true`. 33) Returns `bool(opt) ? *opt <=> value : std::strong_ordering::less`. ### Exceptions 1-7) May throw implementation-defined exceptions. 21-33) Throws when and what the comparison throws. ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 2945](https://cplusplus.github.io/LWG/issue2945) | C++17 | order of template parameters inconsistent for compare-with-T cases | made consistent | cpp std::optional<T>::value_or std::optional<T>::value\_or =========================== | | | | | --- | --- | --- | | ``` template< class U > constexpr T value_or( U&& default_value ) const&; ``` | (1) | (since C++17) | | ``` template< class U > constexpr T value_or( U&& default_value ) &&; ``` | (2) | (since C++17) | Returns the contained value if `*this` has a value, otherwise returns `default_value`. 1) Equivalent to `bool(\*this) ? \*\*this : static\_cast<T>([std::forward](http://en.cppreference.com/w/cpp/utility/forward)<U>(default_value))` 2) Equivalent to `bool(\*this) ? std::move(\*\*this) : static\_cast<T>([std::forward](http://en.cppreference.com/w/cpp/utility/forward)<U>(default_value))` ### Parameters | | | | | --- | --- | --- | | default\_value | - | the value to use in case `*this` is empty | | Type requirements | | -`T` must meet the requirements of [CopyConstructible](../../named_req/copyconstructible "cpp/named req/CopyConstructible") in order to use overload (1). | | -`T` must meet the requirements of [MoveConstructible](../../named_req/moveconstructible "cpp/named req/MoveConstructible") in order to use overload (2). | | -`U&&` must be convertible to `T` | ### Return value The current value if `*this` has a value, or `default_value` otherwise. ### Exceptions Any exception thrown by the selected constructor of the return value `T`. ### Example ``` #include <optional> #include <iostream> #include <cstdlib> std::optional<const char*> maybe_getenv(const char* n) { if(const char* x = std::getenv(n)) return x; else return {}; } int main() { std::cout << maybe_getenv("MYPWD").value_or("(none)") << '\n'; } ``` Possible output: ``` (none) ``` ### See also | | | | --- | --- | | [value](value "cpp/utility/optional/value") | returns the contained value (public member function) | cpp std::any::has_value std::any::has\_value ==================== | | | | | --- | --- | --- | | ``` bool has_value() const noexcept; ``` | | (since C++17) | Checks whether the object contains a value. ### Parameters (none). ### Return value `true` if instance contains a value, otherwise `false`. ### Example ``` #include <any> #include <iostream> #include <string> int main() { std::boolalpha(std::cout); std::any a0; std::cout << "a0.has_value(): " << a0.has_value() << "\n"; std::any a1 = 42; std::cout << "a1.has_value(): " << a1.has_value() << '\n'; std::cout << "a1 = " << std::any_cast<int>(a1) << '\n'; a1.reset(); std::cout << "a1.has_value(): " << a1.has_value() << '\n'; auto a2 = std::make_any<std::string>("Milky Way"); std::cout << "a2.has_value(): " << a2.has_value() << '\n'; std::cout << "a2 = \"" << std::any_cast<std::string&>(a2) << "\"\n"; a2.reset(); std::cout << "a2.has_value(): " << a2.has_value() << '\n'; } ``` Output: ``` a0.has_value(): false a1.has_value(): true a1 = 42 a1.has_value(): false a2.has_value(): true a2 = "Milky Way" a2.has_value(): false ``` ### See also | | | | --- | --- | | [reset](reset "cpp/utility/any/reset") | destroys contained object (public member function) | cpp std::any::reset std::any::reset =============== | | | | | --- | --- | --- | | ``` void reset() noexcept; ``` | | (since C++17) | If not empty, destroys the contained object. ### Parameters (none). ### Return value (none). ### See also | | | | --- | --- | | [has\_value](has_value "cpp/utility/any/has value") | checks if object holds a value (public member function) | cpp std::any::any std::any::any ============= | | | | | --- | --- | --- | | ``` constexpr any() noexcept; ``` | (1) | (since C++17) | | ``` any( const any& other ); ``` | (2) | (since C++17) | | ``` any( any&& other ) noexcept; ``` | (3) | (since C++17) | | ``` template< class ValueType > any( ValueType&& value ); ``` | (4) | (since C++17) | | ``` template< class ValueType, class... Args > explicit any( std::in_place_type_t<ValueType>, Args&&... args ); ``` | (5) | (since C++17) | | ``` template< class ValueType, class U, class... Args > explicit any( std::in_place_type_t<ValueType>, std::initializer_list<U> il, Args&&... args ); ``` | (6) | (since C++17) | Constructs a new `any` object. 1) Constructs an empty object. 2-3) Copies (2) or moves (3) content of `other` into a new instance, so that any content is equivalent in both type and value to those of `other` prior to the constructor call, or empty if `other` is empty. Formally, 2) If `other` is empty, the constructed object is empty. Otherwise, equivalent to `any([std::in\_place\_type](http://en.cppreference.com/w/cpp/utility/in_place)<T>, [std::any\_cast](http://en.cppreference.com/w/cpp/utility/any/any_cast)<const T&>(other))`, where `T` is the type of the object contained in `other`. 3) If `other` is empty, the constructed object is empty. Otherwise, the constructed object contains either the object contained in `other`, or an object of the same type constructed from the object contained in `other`, considering that object as an rvalue. 4) Constructs an object with initial content an object of type `[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<ValueType>`, [direct-initialized](../../language/direct_initialization "cpp/language/direct initialization") from `[std::forward](http://en.cppreference.com/w/cpp/utility/forward)<ValueType>(value)`. * This overload participates in overload resolution only if `[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<ValueType>` is not the same type as `any` nor a specialization of `[std::in\_place\_type\_t](../in_place "cpp/utility/in place")`, and `[std::is\_copy\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_copy_constructible)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<ValueType>>` is `true`. 5) Constructs an object with initial content an object of type `[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<ValueType>`, [direct-non-list-initialized](../../language/direct_initialization "cpp/language/direct initialization") from `[std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Args>(args)...`. * This overload participates in overload resolution only if `[std::is\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_constructible)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<ValueType>, Args...>` and `[std::is\_copy\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_copy_constructible)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<ValueType>>` are both `true`. 6) Constructs an object with initial content an object of type `[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<ValueType>`, [direct-non-list-initialized](../../language/direct_initialization "cpp/language/direct initialization") from `il, [std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Args>(args)...`. * This overload participates in overload resolution only if `[std::is\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_constructible)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<ValueType>, [std::initializer\_list](http://en.cppreference.com/w/cpp/utility/initializer_list)<U>&, Args...>` and `[std::is\_copy\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_copy_constructible)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<ValueType>>` are both `true`. ### Template parameters | | | | | --- | --- | --- | | ValueType | - | contained value type | | Type requirements | | -`std::decay_t<ValueType>` must meet the requirements of [CopyConstructible](../../named_req/copyconstructible "cpp/named req/CopyConstructible"). | ### Parameters | | | | | --- | --- | --- | | other | - | another `any` object to copy or move from | | value | - | value to initialize the contained value with | | il, args | - | arguments to be passed to the constructor of the contained object | ### Exceptions 2,4,5,6) Throws any exception thrown by the constructor of the contained type. ### Notes Because the default constructor is `constexpr`, static `std::any`s are initialized as part of [static non-local initialization](../../language/initialization#Non-local_variables "cpp/language/initialization"), before any dynamic non-local initialization begins. This makes it safe to use an object of type `std::any` in a constructor of any static object. ### Example ``` #include <utility> #include <set> #include <any> #include <string> #include <memory> #include <iostream> #include <initializer_list> #include <cxxabi.h> struct A { int age; std::string name; double salary; }; // using abi demangle to print nice type name of instance of any holding void printType(const std::any& a) { int status; if (char* p = abi::__cxa_demangle(a.type().name(), 0, 0, &status)){ std::cout << p << '\n'; std::free(p); } } int main(){ // constructor #4: std::any holding int std::any a1{7}; // constructor #5: std::any holding A, constructed in place std::any a2(std::in_place_type_t<A>{}, 30, "Ada", 1000.25); // constructor #6: std::any holding a set of A with custom comparison auto lambda = [](auto&& l, auto&& r){ return l.age < r.age; }; std::any a3( std::in_place_type_t<std::set<A, decltype(lambda)>>{}, std::initializer_list<A>{ {39, std::string{"Ada"}, 100.25}, {20, std::string{"Bob"}, 75.5} }, lambda); printType(a1); printType(a2); printType(a3); } ``` Possible output: ``` int A std::set<A, main::{lambda(auto:1&&, auto:2&&)#1}, std::allocator<A> > ``` ### See also | | | | --- | --- | | [operator=](operator= "cpp/utility/any/operator=") | assigns an `any` object (public member function) |
programming_docs
cpp std::any::emplace std::any::emplace ================= | | | | | --- | --- | --- | | ``` template< class ValueType, class... Args > std::decay_t<ValueType>& emplace( Args&&... args ); ``` | (1) | (since C++17) | | ``` template< class ValueType, class U, class... Args > std::decay_t<ValueType>& emplace( std::initializer_list<U> il, Args&&... args ); ``` | (2) | (since C++17) | Changes the contained object to one of type `[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<ValueType>` constructed from the arguments. First destroys the current contained object (if any) by `[reset()](reset "cpp/utility/any/reset")`, then: 1) constructs an object of type `[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<ValueType>`, [direct-non-list-initialized](../../language/direct_initialization "cpp/language/direct initialization") from `[std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Args>(args)...`, as the contained object. * This overload participates in overload resolution only if `[std::is\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_constructible)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<ValueType>, Args...>` and `[std::is\_copy\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_copy_constructible)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<ValueType>>` are both `true`. 2) constructs an object of type `[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<ValueType>`, [direct-non-list-initialized](../../language/direct_initialization "cpp/language/direct initialization") from `il, [std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Args>(args)...`, as the contained object. * This overload participates in overload resolution only if `[std::is\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_constructible)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<ValueType>, [std::initializer\_list](http://en.cppreference.com/w/cpp/utility/initializer_list)<U>&, Args...>` and `[std::is\_copy\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_copy_constructible)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<ValueType>>` are both `true`. ### Template parameters | | | | | --- | --- | --- | | ValueType | - | contained value type | | Type requirements | | -`std::decay_t<ValueType>` must meet the requirements of [CopyConstructible](../../named_req/copyconstructible "cpp/named req/CopyConstructible"). | ### Return value A reference to the new contained object. ### Exceptions Throws any exception thrown by `T`'s constructor. If an exception is thrown, the previously contained object (if any) has been destroyed, and `*this` does not contain a value. ### Example ``` #include <algorithm> #include <any> #include <iostream> #include <string> #include <vector> class Star { std::string name; int id; public: Star(std::string name, int id) : name { name }, id { id } { std::cout << "Star::Star(string, int)\n"; } void print() const { std::cout << "Star{ \"" << name << "\" : " << id << " };\n"; } }; auto main() -> int { std::any celestial; // (1) emplace( Args&&... args ); celestial.emplace<Star>("Procyon", 2943); const auto* star = std::any_cast<Star>(&celestial); star->print(); std::any av; // (2) emplace( std::initializer_list<U> il, Args&&... args ); av.emplace<std::vector<char>>({ 'C', '+', '+', '1', '7' } /* no args */ ); std::cout << av.type().name() << '\n'; const auto* va = std::any_cast<std::vector<char>>(&av); std::for_each(va->cbegin(), va->cend(), [](char const& c) { std::cout << c; }); std::cout << '\n'; } ``` Possible output: ``` Star::Star(string, int) Star{ "Procyon" : 2943 }; St6vectorIcSaIcEE C++17 ``` ### See also | | | | --- | --- | | [(constructor)](any "cpp/utility/any/any") | constructs an `any` object (public member function) | | [reset](reset "cpp/utility/any/reset") | destroys contained object (public member function) | cpp std::any::type std::any::type ============== | | | | | --- | --- | --- | | ``` const std::type_info& type() const noexcept; ``` | | (since C++17) | Queries the contained type. ### Parameters (none). ### Return value The `typeid` of the contained value if instance is non-empty, otherwise `typeid(void)`. ### Example The example demonstrates `std::any` visitor idiom with ability to register new visitors at compile- and run-time. ``` #include <type_traits> #include <any> #include <functional> #include <iomanip> #include <iostream> #include <typeindex> #include <typeinfo> #include <unordered_map> #include <vector> template<class T, class F> inline std::pair<const std::type_index, std::function<void(std::any const&)>> to_any_visitor(F const &f) { return { std::type_index(typeid(T)), [g = f](std::any const &a) { if constexpr (std::is_void_v<T>) g(); else g(std::any_cast<T const&>(a)); } }; } static std::unordered_map< std::type_index, std::function<void(std::any const&)>> any_visitor { to_any_visitor<void>([]{ std::cout << "{}"; }), to_any_visitor<int>([](int x){ std::cout << x; }), to_any_visitor<unsigned>([](unsigned x){ std::cout << x; }), to_any_visitor<float>([](float x){ std::cout << x; }), to_any_visitor<double>([](double x){ std::cout << x; }), to_any_visitor<char const*>([](char const *s) { std::cout << std::quoted(s); }), // ... add more handlers for your types ... }; inline void process(const std::any& a) { if (const auto it = any_visitor.find(std::type_index(a.type())); it != any_visitor.cend()) { it->second(a); } else { std::cout << "Unregistered type "<< std::quoted(a.type().name()); } } template<class T, class F> inline void register_any_visitor(F const& f) { std::cout << "Register visitor for type " << std::quoted(typeid(T).name()) << '\n'; any_visitor.insert(to_any_visitor<T>(f)); } auto main() -> int { std::vector<std::any> va { {}, 42, 123u, 3.14159f, 2.71828, "C++17", }; std::cout << "{ "; for (const std::any& a : va) { process(a); std::cout << ", "; } std::cout << "}\n"; process(std::any(0xFULL)); //< Unregistered type "y" (unsigned long long) std::cout << '\n'; register_any_visitor<unsigned long long>([](auto x) { std::cout << std::hex << std::showbase << x; }); process(std::any(0xFULL)); //< OK: 0xf std::cout << '\n'; } ``` Possible output: ``` { {}, 42, 123, 3.14159, 2.71828, "C++17", } Unregistered type "y" Register visitor for type "y" 0xf ``` ### See also | | | | --- | --- | | [type\_index](../../types/type_index "cpp/types/type index") (C++11) | wrapper around a `type_info` object, that can be used as index in associative and unordered associative containers (class) | cpp std::any::swap std::any::swap ============== | | | | | --- | --- | --- | | ``` void swap(any& other) noexcept; ``` | | (since C++17) | Swaps the content of two `any` objects. ### Parameters | | | | | --- | --- | --- | | other | - | object to swap with | ### Return value (none). cpp std::swap(std::any) std::swap(std::any) =================== | | | | | --- | --- | --- | | ``` void swap(any& lhs, any& rhs) noexcept; ``` | | (since C++17) | Overloads the `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` algorithm for `[std::any](../any "cpp/utility/any")`. Swaps the content of two `any` objects by calling `lhs.swap(rhs)`. ### Parameters | | | | | --- | --- | --- | | lhs, rhs | - | objects to swap | ### Return value (none). ### See also | | | | --- | --- | | [swap](swap "cpp/utility/any/swap") | swaps two `any` objects (public member function) | cpp std::make_any std::make\_any ============== | | | | | --- | --- | --- | | ``` template< class T, class... Args > std::any make_any( Args&&... args ); ``` | (1) | (since C++17) | | ``` template< class T, class U, class... Args > std::any make_any( std::initializer_list<U> il, Args&&... args ); ``` | (2) | (since C++17) | Constructs an `any` object containing an object of type `T`, passing the provided arguments to `T`'s constructor. 1) Equivalent to `return [std::any](http://en.cppreference.com/w/cpp/utility/any)([std::in\_place\_type](http://en.cppreference.com/w/cpp/utility/in_place)<T>, [std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Args>(args)...);` 2) Equivalent to `return [std::any](http://en.cppreference.com/w/cpp/utility/any)([std::in\_place\_type](http://en.cppreference.com/w/cpp/utility/in_place)<T>, il, [std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Args>(args)...);` ### Example ``` #include <any> #include <complex> #include <functional> #include <iostream> #include <string> int main() { auto a0 = std::make_any<std::string>("Hello, std::any!\n"); auto a1 = std::make_any<std::complex<double>>(0.1, 2.3); std::cout << std::any_cast<std::string&>(a0); std::cout << std::any_cast<std::complex<double>&>(a1) << '\n'; using lambda = std::function<void(void)>; // Put a lambda into std::any. Attempt #1 (failed). std::any a2 = [] { std::cout << "Lambda #1.\n"; }; std::cout << "a2.type() = \"" << a2.type().name() << "\"\n"; // any_cast casts to <void(void)> but actual type is not // a std::function..., but ~ main::{lambda()#1}, and it is // unique for each lambda. So, this throws... try { std::any_cast<lambda>(a2)(); } catch (std::bad_any_cast const& ex) { std::cout << ex.what() << '\n'; } // Put a lambda into std::any. Attempt #2 (successful). auto a3 = std::make_any<lambda>([] { std::cout << "Lambda #2.\n"; }); std::cout << "a3.type() = \"" << a3.type().name() << "\"\n"; std::any_cast<lambda>(a3)(); } ``` Possible output: ``` Hello, std::any! (0.1,2.3) a2.type() = "Z4mainEUlvE_" bad any_cast a3.type() = "St8functionIFvvEE" Lambda #2. ``` ### See also | | | | --- | --- | | [(constructor)](any "cpp/utility/any/any") | constructs an `any` object (public member function) | | [any\_cast](any_cast "cpp/utility/any/any cast") (C++17) | type-safe access to the contained object (function template) | cpp std::any::~any std::any::~any ============== | | | | | --- | --- | --- | | ``` ~any(); ``` | | (since C++17) | Destroys the contained object, if any, as if by a call to `reset()`. ### See also | | | | --- | --- | | [reset](reset "cpp/utility/any/reset") | destroys contained object (public member function) | cpp std::any::operator= std::any::operator= =================== | | | | | --- | --- | --- | | ``` any& operator=( const any& rhs ); ``` | (1) | (since C++17) | | ``` any& operator=( any&& rhs ) noexcept; ``` | (2) | (since C++17) | | ``` template<typename ValueType> any& operator=( ValueType&& rhs ); ``` | (3) | (since C++17) | Assigns contents to the contained value. 1) Assigns by copying the state of `rhs`, as if by `any(rhs).swap(*this)`. 2) Assigns by moving the state of `rhs`, as if by `any(std::move(rhs)).swap(*this)`. `rhs` is left in a valid but unspecified state after the assignment. 3) Assigns the type and value of `rhs`, as if by `any([std::forward](http://en.cppreference.com/w/cpp/utility/forward)<ValueType>(rhs)).swap(\*this)`. This overload participates in overload resolution only if `[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<ValueType>` is not the same type as `any` and `[std::is\_copy\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_copy_constructible)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<ValueType>>` is `true`. . ### Template parameters | | | | | --- | --- | --- | | ValueType | - | contained value type | | Type requirements | | -`std::decay_t<ValueType>` must meet the requirements of [CopyConstructible](../../named_req/copyconstructible "cpp/named req/CopyConstructible"). | ### Parameters | | | | | --- | --- | --- | | rhs | - | object whose contained value to assign | ### Return value `*this`. ### Exceptions 1,3) Throws `bad_alloc` or any exception thrown by the constructor of the contained type. If an exception is thrown, there are no effects (strong exception guarantee). ### Example ### See also | | | | --- | --- | | [(constructor)](any "cpp/utility/any/any") | constructs an `any` object (public member function) | cpp std::bad_any_cast std::bad\_any\_cast =================== | Defined in header `[<any>](../../header/any "cpp/header/any")` | | | | --- | --- | --- | | ``` class bad_any_cast : public std::bad_cast; ``` | | (since C++17) | Defines a type of object to be thrown by the value-returning forms of `[std::any\_cast](any_cast "cpp/utility/any/any cast")` on failure. ### Member functions | | | | --- | --- | | (constructor) | constructs a new `bad_any_cast` object (public member function) | | operator= | replaces the `bad_any_cast` object (public member function) | | what | returns the explanatory string (public member function) | std::bad\_any\_cast::bad\_any\_cast ------------------------------------ | | | | | --- | --- | --- | | ``` bad_any_cast() noexcept; ``` | (1) | (since C++17) | | ``` bad_any_cast( const bad_any_cast& other ) noexcept; ``` | (2) | (since C++17) | Constructs a new `bad_any_cast` object with an implementation-defined null-terminated byte string which is accessible through [`what()`](../../error/exception/what "cpp/error/exception/what"). 1) Default constructor. 2) Copy constructor. If `*this` and `other` both have dynamic type `std::bad_any_cast` then `[std::strcmp](http://en.cppreference.com/w/cpp/string/byte/strcmp)(what(), other.what()) == 0`. ### Parameters | | | | | --- | --- | --- | | other | - | another exception object to copy | std::bad\_any\_cast::operator= ------------------------------- | | | | | --- | --- | --- | | ``` bad_any_cast& operator=( const bad_any_cast& other ) noexcept; ``` | | (since C++17) | Assigns the contents with those of `other`. If `*this` and `other` both have dynamic type `std::bad_any_cast` then `[std::strcmp](http://en.cppreference.com/w/cpp/string/byte/strcmp)(what(), other.what()) == 0` after assignment. ### Parameters | | | | | --- | --- | --- | | other | - | another exception object to assign with | ### Return value `*this`. std::bad\_any\_cast::what -------------------------- | | | | | --- | --- | --- | | ``` virtual const char* what() const noexcept; ``` | | (since C++17) | Returns the explanatory string. ### Parameters (none). ### Return value Pointer to a null-terminated string with explanatory information. The string is suitable for conversion and display as a `[std::wstring](../../string/basic_string "cpp/string/basic string")`. The pointer is guaranteed to be valid at least until the exception object from which it is obtained is destroyed, or until a non-const member function (e.g. copy assignment operator) on the exception object is called. ### Notes Implementations are allowed but not required to override `what()`. Inherited from [std::bad\_cast](../../types/bad_cast "cpp/types/bad cast") --------------------------------------------------------------------------- Inherited from [std::exception](../../error/exception "cpp/error/exception") ------------------------------------------------------------------------------ ### Member functions | | | | --- | --- | | [(destructor)](../../error/exception/~exception "cpp/error/exception/~exception") [virtual] | destroys the exception object (virtual public member function of `std::exception`) | | [what](../../error/exception/what "cpp/error/exception/what") [virtual] | returns an explanatory string (virtual public member function of `std::exception`) | cpp std::any_cast std::any\_cast ============== | | | | | --- | --- | --- | | ``` template<class T> T any_cast(const any& operand); ``` | (1) | (since C++17) | | ``` template<class T> T any_cast(any& operand); ``` | (2) | (since C++17) | | ``` template<class T> T any_cast(any&& operand); ``` | (3) | (since C++17) | | ``` template<class T> const T* any_cast(const any* operand) noexcept; ``` | (4) | (since C++17) | | ``` template<class T> T* any_cast(any* operand) noexcept; ``` | (5) | (since C++17) | Performs type-safe access to the contained object. Let `U` be `[std::remove\_cv\_t](http://en.cppreference.com/w/cpp/types/remove_cv)<[std::remove\_reference\_t](http://en.cppreference.com/w/cpp/types/remove_reference)<T>>`. 1) The program is ill-formed if `[std::is\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_constructible)<T, const U&>` is `false`. 2) The program is ill-formed if `[std::is\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_constructible)<T, U&>` is `false`. 3) The program is ill-formed if `[std::is\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_constructible)<T, U>` is `false`. ### Parameters | | | | | --- | --- | --- | | operand | - | target `any` object | ### Return value 1-2) Returns `static_cast<T>(*std::any_cast<U>(&operand))` 3) Returns `static_cast<T>(std::move(*std::any_cast<U>(&operand)))`. 4-5) If `operand` is not a null pointer, and the `typeid` of the requested `T` matches that of the contents of `operand`, a pointer to the value contained by operand, otherwise a null pointer. ### Exceptions 1-3) Throws `[std::bad\_any\_cast](bad_any_cast "cpp/utility/any/bad any cast")` if the `typeid` of the requested `T` does not match that of the contents of `operand`. ### Example ``` #include <string> #include <iostream> #include <any> #include <utility> int main() { // simple example auto a = std::any(12); std::cout << std::any_cast<int>(a) << '\n'; try { std::cout << std::any_cast<std::string>(a) << '\n'; } catch(const std::bad_any_cast& e) { std::cout << e.what() << '\n'; } // pointer example if (int* i = std::any_cast<int>(&a)) { std::cout << "a is int: " << *i << '\n'; } else if (std::string* s = std::any_cast<std::string>(&a)) { std::cout << "a is std::string: " << *s << '\n'; } else { std::cout << "a is another type or unset\n"; } // advanced example a = std::string("hello"); auto& ra = std::any_cast<std::string&>(a); //< reference ra[1] = 'o'; std::cout << "a: " << std::any_cast<const std::string&>(a) << '\n'; //< const reference auto b = std::any_cast<std::string&&>(std::move(a)); //< rvalue reference // Note: 'b' is a move-constructed std::string, // 'a' is left in valid but unspecified state std::cout << "a: " << *std::any_cast<std::string>(&a) //< pointer << "b: " << b << '\n'; } ``` Possible output: ``` 12 bad any_cast a is int: 12 a: hollo a: b: hollo ``` cpp std::initializer_list<T>::size std::initializer\_list<T>::size =============================== | | | | | --- | --- | --- | | ``` size_type size() const noexcept; ``` | | (since C++11) (until C++14) | | ``` constexpr size_type size() const noexcept; ``` | | (since C++14) | Returns the number of elements in the initializer list, i.e. `[std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(begin(), end())`. ### Parameters (none). ### Return value the number of elements in the initializer list. ### Complexity Constant. ### Example ``` #include <initializer_list> int main() { static_assert(std::initializer_list{1,2,3,4}.size() == 4); } ```
programming_docs
cpp std::initializer_list<T>::initializer_list std::initializer\_list<T>::initializer\_list ============================================ | | | | | --- | --- | --- | | ``` initializer_list() noexcept; ``` | | (since C++11) (until C++14) | | ``` constexpr initializer_list() noexcept; ``` | | (since C++14) | Constructs an empty initializer list. ### Parameters (none). ### Complexity Constant. ### Example ``` #include <iostream> #include <initializer_list> int main() { std::initializer_list<int> empty_list; std::cout << "empty_list.size(): " << empty_list.size() << '\n'; // create initializer lists using list-initialization std::initializer_list<int> digits {1, 2, 3, 4, 5}; std::cout << "digits.size(): " << digits.size() << '\n'; // special rule for auto means 'fractions' has the // type std::initializer_list<double> auto fractions = {3.14159, 2.71828}; std::cout << "fractions.size(): " << fractions.size() << '\n'; } ``` Output: ``` empty_list.size(): 0 digits.size(): 5 fractions.size(): 2 ``` ### Notes Despite a lack of constructors, it is possible to create non-empty initializer lists. Instances of `std::initializer_list` are implicitly constructed when: * a *braced-init-list* is used in [list-initialization](../../language/list_initialization "cpp/language/list initialization"), including function-call list initialization and assignment expressions (not to be confused with [constructor initializer lists](../../language/initializer_list "cpp/language/initializer list")) * a *braced-init-list* is bound to `auto`, including in a [ranged for loop](../../language/range-for "cpp/language/range-for") cpp std::end(std::initializer_list) std::end(std::initializer\_list) ================================ | Defined in header `[<initializer\_list>](../../header/initializer_list "cpp/header/initializer list")` | | | | --- | --- | --- | | ``` template< class E > const E* end( std::initializer_list<E> il ) noexcept; ``` | | (since C++11) (until C++14) | | ``` template< class E > constexpr const E* end( std::initializer_list<E> il ) noexcept; ``` | | (since C++14) | The overload of `[std::end](../../iterator/end "cpp/iterator/end")` for `initializer_list` returns a pointer to one past the last element of `il`. ### Parameters | | | | | --- | --- | --- | | il | - | an `initializer_list` | ### Return value `il.end()`. ### Example ``` #include <iostream> int main() { // range-based for uses std::begin and std::end to iterate // over a given range; in this case, it's an initializer list for (int i : {3, 1, 4, 1}) { std::cout << i << '\n'; } } ``` Output: ``` 3 1 4 1 ``` ### See also | | | | --- | --- | | [end](end "cpp/utility/initializer list/end") | returns a pointer to one past the last element (public member function) | cpp std::initializer_list<T>::begin std::initializer\_list<T>::begin ================================ | | | | | --- | --- | --- | | ``` const T* begin() const noexcept; ``` | | (since C++11) (until C++14) | | ``` constexpr const T* begin() const noexcept; ``` | | (since C++14) | Returns a pointer to the first element in the initializer list. If the initializer list is empty, the values of `begin()` and `[end()](end "cpp/utility/initializer list/end")` are unspecified, but will be identical. ### Parameters (none). ### Return value a pointer to the first element in the initializer list. ### Complexity Constant. ### See also | | | | --- | --- | | [end](end "cpp/utility/initializer list/end") | returns a pointer to one past the last element (public member function) | cpp std::begin(std::initializer_list) std::begin(std::initializer\_list) ================================== | Defined in header `[<initializer\_list>](../../header/initializer_list "cpp/header/initializer list")` | | | | --- | --- | --- | | ``` template< class E > const E* begin( std::initializer_list<E> il ) noexcept; ``` | | (since C++11) (until C++14) | | ``` template< class E > constexpr const E* begin( std::initializer_list<E> il ) noexcept; ``` | | (since C++14) | The overload of `[std::begin](../../iterator/begin "cpp/iterator/begin")` for `initializer_list` returns a pointer to the first element of `il`. ### Parameters | | | | | --- | --- | --- | | il | - | an `initializer_list` | ### Return value `il.begin()`. ### Example ``` #include <iostream> #include <initializer_list> int main() { std::initializer_list<int> il = {3, 1, 4, 1}; for(auto it = std::begin(il); it != std::end(il); ++it) { std::cout << *it << '\n'; } } ``` Output: ``` 3 1 4 1 ``` ### See also | | | | --- | --- | | [begin](begin "cpp/utility/initializer list/begin") | returns a pointer to the first element (public member function) | cpp std::initializer_list<T>::end std::initializer\_list<T>::end ============================== | | | | | --- | --- | --- | | ``` const T* end() const noexcept; ``` | | (since C++11) (until C++14) | | ``` constexpr const T* end() const noexcept; ``` | | (since C++14) | Returns a pointer to one past the last element in the initializer list, i.e. `begin() + size()`. If the initializer list is empty, the values of `[begin()](begin "cpp/utility/initializer list/begin")` and `end()` are unspecified, but will be identical. ### Parameters (none). ### Return value a pointer to one past the last element in the initializer list. ### Complexity Constant. ### See also | | | | --- | --- | | [begin](begin "cpp/utility/initializer list/begin") | returns a pointer to the first element (public member function) | cpp std::strong_ordering std::strong\_ordering ===================== | Defined in header `[<compare>](../../header/compare "cpp/header/compare")` | | | | --- | --- | --- | | ``` class strong_ordering; ``` | | (since C++20) | The class type `std::strong_ordering` is the result type of a [three-way comparison](../../language/operator_comparison#Three-way_comparison "cpp/language/operator comparison") that. * admits all six relational operators (==, !=, <, <=, >, >=) * implies substitutability: if a is equivalent to b, f(a) is also equivalent to f(b), where f denotes a function that reads only comparison-salient state that is accessible via the argument's public const members. In other words, equivalent values are indistinguishable. * does not allow incomparable values: exactly one of a < b, a == b, or a > b must be true ### Constants The type `std::strong_ordering` has four valid values, implemented as const static data members of its type: | Member constant | Definition | | --- | --- | | less(inline constexpr) [static] | a valid value of the type `std::strong_ordering` indicating less-than (ordered before) relationship (public static member constant) | | equivalent(inline constexpr) [static] | a valid value of the type `std::strong_ordering` indicating equivalence (neither ordered before nor ordered after), the same as `equal` (public static member constant) | | equal(inline constexpr) [static] | a valid value of the type `std::strong_ordering` indicating equivalence (neither ordered before nor ordered after), the same as `equivalent` (public static member constant) | | greater(inline constexpr) [static] | a valid value of the type `std::strong_ordering` indicating greater-than (ordered after) relationship (public static member constant) | ### Conversions `std::strong_ordering` is the strongest of the three comparison categories: it is not implicitly-convertible from any other category and is implicitly-convertible to the other two. | | | | --- | --- | | **operator partial\_ordering** | implicit conversion to `std::partial_ordering` (public member function) | std::strong\_ordering::operator partial\_ordering -------------------------------------------------- | | | | | --- | --- | --- | | ``` constexpr operator partial_ordering() const noexcept; ``` | | | ### Return value `std::partial_ordering::less` if `v` is `less`, `std::partial_ordering::greater` if `v` is `greater`, `std::partial_ordering::equivalent` if `v` is `equal` or `equivalent`. | | | | --- | --- | | **operator weak\_ordering** | implicit conversion to `std::weak_ordering` (public member function) | std::strong\_ordering::operator weak\_ordering ----------------------------------------------- | | | | | --- | --- | --- | | ``` constexpr operator weak_ordering() const noexcept; ``` | | | ### Return value `std::weak_ordering::less` if `v` is `less`, `std::weak_ordering::greater` if `v` is `greater`, `std::weak_ordering::equivalent` if `v` is `equal` or `equivalent`. ### Comparisons Comparison operators are defined between values of this type and literal `​0​`. This supports the expressions `a <=> b == 0` or `a <=> b < 0` that can be used to convert the result of a three-way comparison operator to a boolean relationship; see [`std::is_eq`](named_comparison_functions "cpp/utility/compare/named comparison functions"), [`std::is_lt`](named_comparison_functions "cpp/utility/compare/named comparison functions"), etc. These functions are not visible to ordinary [unqualified](../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../language/adl "cpp/language/adl") when `std::strong_ordering` is an associated class of the arguments. The behavior of a program that attempts to compare a `strong_ordering` with anything other than the integer literal `​0​` is undefined. | | | | --- | --- | | **operator==operator<operator>operator<=operator>=operator<=>** | compares with zero or a `strong_ordering` (function) | operator== ----------- | | | | | --- | --- | --- | | ``` friend constexpr bool operator==(strong_ordering v, /*unspecified*/ u) noexcept; ``` | (1) | | | ``` friend constexpr bool operator==(strong_ordering v, strong_ordering w) noexcept = default; ``` | (2) | | ### Parameters | | | | | --- | --- | --- | | v, w | - | `std::strong_ordering` values to check | | u | - | an unused parameter of any type that accepts literal zero argument | ### Return value 1) `true` if `v` is `equivalent` or `equal`, `false` if `v` is `less` or `greater` 2) `true` if both parameters hold the same value, `false` otherwise. Note that `equal` is the same as `equivalent`. operator< ---------- | | | | | --- | --- | --- | | ``` friend constexpr bool operator<(strong_ordering v, /*unspecified*/ u) noexcept; ``` | (1) | | | ``` friend constexpr bool operator<(/*unspecified*/ u, strong_ordering v) noexcept; ``` | (2) | | ### Parameters | | | | | --- | --- | --- | | v | - | a `std::strong_ordering` value to check | | u | - | an unused parameter of any type that accepts literal zero argument | ### Return value 1) `true` if `v` is `less`, and `false` if `v` is `greater`, `equivalent`, or `equal` 2) `true` if `v` is `greater`, and `false` if `v` is `less`, `equivalent`, or `equal` operator<= ----------- | | | | | --- | --- | --- | | ``` friend constexpr bool operator<=(strong_ordering v, /*unspecified*/ u) noexcept; ``` | (1) | | | ``` friend constexpr bool operator<=(/*unspecified*/ u, strong_ordering v) noexcept; ``` | (2) | | ### Parameters | | | | | --- | --- | --- | | v | - | a `std::strong_ordering` value to check | | u | - | an unused parameter of any type that accepts literal zero argument | ### Return value 1) `true` if `v` is `less`, `equivalent`, or `equal`, and `false` if `v` is `greater` 2) `true` if `v` is `greater`, `equivalent`, or `equal`, and `false` if `v` is `less` operator> ---------- | | | | | --- | --- | --- | | ``` friend constexpr bool operator>(strong_ordering v, /*unspecified*/ u) noexcept; ``` | (1) | | | ``` friend constexpr bool operator>(/*unspecified*/ u, strong_ordering v) noexcept; ``` | (2) | | ### Parameters | | | | | --- | --- | --- | | v | - | a `std::strong_ordering` value to check | | u | - | an unused parameter of any type that accepts literal zero argument | ### Return value 1) `true` if `v` is `greater`, and `false` if `v` is `less`, `equivalent`, or `equal` 2) `true` if `v` is `less`, and `false` if `v` is `greater`, `equivalent`, or `equal` operator>= ----------- | | | | | --- | --- | --- | | ``` friend constexpr bool operator>=(strong_ordering v, /*unspecified*/ u) noexcept; ``` | (1) | | | ``` friend constexpr bool operator>=(/*unspecified*/ u, strong_ordering v) noexcept; ``` | (2) | | ### Parameters | | | | | --- | --- | --- | | v | - | a `std::strong_ordering` value to check | | u | - | an unused parameter of any type that accepts literal zero argument | ### Return value 1) `true` if `v` is `greater`, `equivalent`, or `equal`, and `false` if `v` is `less` 2) `true` if `v` is `less`, `equivalent`, or `equal`, and `false` if `v` is `greater` operator<=> ------------ | | | | | --- | --- | --- | | ``` friend constexpr strong_ordering operator<=>(strong_ordering v, /*unspecified*/ u) noexcept; ``` | (1) | | | ``` friend constexpr strong_ordering operator<=>(/*unspecified*/ u, strong_ordering v) noexcept; ``` | (2) | | ### Parameters | | | | | --- | --- | --- | | v | - | a `std::strong_ordering` value to check | | u | - | an unused parameter of any type that accepts literal zero argument | ### Return value 1) `v`. 2) `greater` if `v` is `less`, `less` if `v` is `greater`, otherwise `v`. ### Example ### See also | | | | --- | --- | | [weak\_ordering](weak_ordering "cpp/utility/compare/weak ordering") (C++20) | the result type of 3-way comparison that supports all 6 operators and is not substitutable (class) | | [partial\_ordering](partial_ordering "cpp/utility/compare/partial ordering") (C++20) | the result type of 3-way comparison that supports all 6 operators, is not substitutable, and allows incomparable values (class) | cpp std::weak_order std::weak\_order ================ | Defined in header `[<compare>](../../header/compare "cpp/header/compare")` | | | | --- | --- | --- | | ``` inline namespace /* unspecified */ { inline constexpr /* unspecified */ weak_order = /* unspecified */; } ``` | | (since C++20) | | Call signature | | | | ``` template< class T, class U > requires /* see below */ constexpr std::weak_ordering weak_order(T&& t, U&& u) noexcept(/* see below */); ``` | | | Compares two values using 3-way comparison and produces a result of type `std::weak_ordering`. Let `t` and `u` be expressions and `T` and `U` denote `decltype((t))` and `decltype((u))` respectively, `std::weak_order(t, u)` is expression-equivalent to: * If `[std::is\_same\_v](http://en.cppreference.com/w/cpp/types/is_same)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<T>, [std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<U>>` is `true`: + `[std::weak\_ordering](http://en.cppreference.com/w/cpp/utility/compare/weak_ordering)(weak_order(t, u))`, if it is a well-formed expression with overload resolution performed in a context that does not include a declaration of `std::weak_order`, + otherwise, if `T` is a floating-point type: - if `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<T>::is\_iec559` is `true`, performs the weak ordering comparison of floating-point values (see below) and returns that result as a value of type `std::weak_ordering`, - otherwise, yields a value of type `std::weak_ordering` that is consistent with the ordering observed by `T`'s comparison operators, + otherwise, `[std::weak\_ordering](http://en.cppreference.com/w/cpp/utility/compare/weak_ordering)([std::compare\_three\_way](http://en.cppreference.com/w/cpp/utility/compare/compare_three_way)()(t, u))`, if it is well-formed, + otherwise, `[std::weak\_ordering](http://en.cppreference.com/w/cpp/utility/compare/weak_ordering)([std::strong\_order](http://en.cppreference.com/w/cpp/utility/compare/strong_order)(t, u))`, if it is well-formed. * In all other cases, the expression is ill-formed, which can result in [substitution failure](../../language/sfinae "cpp/language/sfinae") when it appears in the immediate context of a template instantiation. ### Expression-equivalent Expression `e` is *expression-equivalent* to expression `f`, if. * `e` and `f` have the same effects, and * either both are [constant subexpressions](../../language/constant_expression "cpp/language/constant expression") or else neither is a constant subexpression, and * either both are [potentially-throwing](../../language/noexcept_spec "cpp/language/noexcept spec") or else neither is potentially-throwing (i.e. `noexcept(e) == noexcept(f)`). ### Customization point objects The name `std::weak_order` denotes a *customization point object*, which is a const [function object](../../named_req/functionobject "cpp/named req/FunctionObject") of a [literal](../../named_req/literaltype "cpp/named req/LiteralType") [`semiregular`](../../concepts/semiregular "cpp/concepts/semiregular") class type. For exposition purposes, the cv-unqualified version of its type is denoted as `*\_\_weak\_order\_fn*`. All instances of `*\_\_weak\_order\_fn*` are equal. The effects of invoking different instances of type `*\_\_weak\_order\_fn*` on the same arguments are equivalent, regardless of whether the expression denoting the instance is an lvalue or rvalue, and is const-qualified or not (however, a volatile-qualified instance is not required to be invocable). Thus, `std::weak_order` can be copied freely and its copies can be used interchangeably. Given a set of types `Args...`, if `[std::declval](http://en.cppreference.com/w/cpp/utility/declval)<Args>()...` meet the requirements for arguments to `std::weak_order` above, `*\_\_weak\_order\_fn*` models . * `[std::invocable](http://en.cppreference.com/w/cpp/concepts/invocable)<__weak_order_fn, Args...>`, * `[std::invocable](http://en.cppreference.com/w/cpp/concepts/invocable)<const __weak_order_fn, Args...>`, * `[std::invocable](http://en.cppreference.com/w/cpp/concepts/invocable)<__weak_order_fn&, Args...>`, and * `[std::invocable](http://en.cppreference.com/w/cpp/concepts/invocable)<const __weak_order_fn&, Args...>`. Otherwise, no function call operator of `*\_\_weak\_order\_fn*` participates in overload resolution. ### Notes #### Strict weak order of IEEE floating-point types Let `x` and `y` be values of same IEEE floating-point type, and `weak_order_less(x, y)` be the boolean result indicating if `x` precedes `y` in the strict weak order defined by the C++ standard. * If neither `x` nor `y` is NaN, then `weak_order_less(x, y) == true` if and only if `x < y`, i.e. all representations of equal floating-point value are equivalent; * If `x` is negative NaN and `y` is not negative NaN, then `weak_order_less(x, y) == true`; * If `x` is not positive NaN and `y` is positive NaN, then `weak_order_less(x, y) == true`; * If both `x` and `y` are NaNs with the same sign, then `(weak_order_less(x, y) || weak_order_less(y, x)) == false`, i.e. all NaNs with the same sign are equivalent. ### Example ### See also | | | | --- | --- | | [weak\_ordering](weak_ordering "cpp/utility/compare/weak ordering") (C++20) | the result type of 3-way comparison that supports all 6 operators and is not substitutable (class) | | [strong\_order](strong_order "cpp/utility/compare/strong order") (C++20) | performs 3-way comparison and produces a result of type `std::strong_ordering` (customization point object) | | [partial\_order](partial_order "cpp/utility/compare/partial order") (C++20) | performs 3-way comparison and produces a result of type `std::partial_ordering` (customization point object) | | [compare\_weak\_order\_fallback](compare_weak_order_fallback "cpp/utility/compare/compare weak order fallback") (C++20) | performs 3-way comparison and produces a result of type `std::weak_ordering`, even if `operator<=>` is unavailable (customization point object) |
programming_docs
cpp std::compare_three_way_result std::compare\_three\_way\_result ================================ | Defined in header `[<compare>](../../header/compare "cpp/header/compare")` | | | | --- | --- | --- | | ``` template<class T, class U = T> struct compare_three_way_result; ``` | | (since C++20) | Let `t` and `u` denote lvalue of `const [std::remove\_reference\_t](http://en.cppreference.com/w/cpp/types/remove_reference)<T>` and `const [std::remove\_reference\_t](http://en.cppreference.com/w/cpp/types/remove_reference)<U>` respectively, if the expression `t <=> u` is well-formed, provides the member typedef `type` equal to `decltype(t <=> u)`, otherwise there is no member `type`. The behavior of a program that adds specializations for `compare_three_way_result` is undefined. ### Member types | Name | Definition | | --- | --- | | `type` | the result type of `operator<=>` on const-qualified lvalue of `T` and `U` | ### Helper types | | | | | --- | --- | --- | | ``` template<class T, class U = T> using compare_three_way_result_t = typename compare_three_way_result<T, U>::type; ``` | | (since C++20) | ### Possible implementation | | | --- | | ``` // recommended by Casey Carter // see also: https://github.com/microsoft/STL/pull/385#discussion_r357894054 template<class T, class U = T> using compare_three_way_result_t = decltype( std::declval<const std::remove_reference_t<T>&>() <=> std::declval<const std::remove_reference_t<U>&>() ); template<class T, class U = T> struct compare_three_way_result {}; template<class T, class U> requires requires { typename compare_three_way_result_t<T, U>; } struct compare_three_way_result<T, U> { using type = compare_three_way_result_t<T, U>; }; ``` | ### Example ``` #include <compare> #include <type_traits> #include <iostream> template <class Ord> void print_cmp_type() { if constexpr (std::is_same_v<Ord, std::strong_ordering>) std::cout << "strong ordering\n"; else if constexpr (std::is_same_v<Ord, std::weak_ordering>) std::cout << "weak ordering\n"; else if constexpr (std::is_same_v<Ord, std::partial_ordering>) std::cout << "partial ordering\n"; else std::cout << "illegal comparison result type\n"; } int main() { print_cmp_type<std::compare_three_way_result_t<int>>(); print_cmp_type<std::compare_three_way_result_t<double>>(); } ``` Output: ``` strong ordering partial ordering ``` ### See also | | | | --- | --- | | [partial\_ordering](partial_ordering "cpp/utility/compare/partial ordering") (C++20) | the result type of 3-way comparison that supports all 6 operators, is not substitutable, and allows incomparable values (class) | | [weak\_ordering](weak_ordering "cpp/utility/compare/weak ordering") (C++20) | the result type of 3-way comparison that supports all 6 operators and is not substitutable (class) | | [strong\_ordering](strong_ordering "cpp/utility/compare/strong ordering") (C++20) | the result type of 3-way comparison that supports all 6 operators and is substitutable (class) | cpp std::compare_weak_order_fallback std::compare\_weak\_order\_fallback =================================== | Defined in header `[<compare>](../../header/compare "cpp/header/compare")` | | | | --- | --- | --- | | ``` inline namespace /* unspecified */ { inline constexpr /* unspecified */ compare_weak_order_fallback = /* unspecified */; } ``` | | (since C++20) | | Call signature | | | | ``` template< class T, class U > requires /* see below */ constexpr std::weak_ordering compare_weak_order_fallback(T&& t, U&& u) noexcept(/* see below */); ``` | | | Performs three-way comparison on `t` and `u` and produces a result of type `std::weak_ordering`, even if the operator `<=>` is unavailable. Let `t` and `u` be expressions and `T` and `U` denote `decltype((t))` and `decltype((u))` respectively, `std::compare_weak_order_fallback(t, u)` is expression-equivalent to: * If `[std::is\_same\_v](http://en.cppreference.com/w/cpp/types/is_same)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<T>, [std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<U>>` is `true`: + `[std::weak\_order](http://en.cppreference.com/w/cpp/utility/compare/weak_order)(t, u)`, if it is a well-formed expression; + otherwise, ``` t == u ? std::weak_ordering::equivalent : t < u ? std::weak_ordering::less : std::weak_ordering::greater ``` if `t == u` and `t < u` are both well-formed and convertible to `bool`, except that `t` and `u` are evaluated only once. * In all other cases, `std::compare_weak_order_fallback(t, u)` is ill-formed, which can result in [substitution failure](../../language/sfinae "cpp/language/sfinae") when it appears in the immediate context of a template instantiation. ### Expression-equivalent Expression `e` is *expression-equivalent* to expression `f`, if. * `e` and `f` have the same effects, and * either both are [constant subexpressions](../../language/constant_expression "cpp/language/constant expression") or else neither is a constant subexpression, and * either both are [potentially-throwing](../../language/noexcept_spec "cpp/language/noexcept spec") or else neither is potentially-throwing (i.e. `noexcept(e) == noexcept(f)`). ### Customization point objects The name `std::compare_weak_order_fallback` denotes a *customization point object*, which is a const [function object](../../named_req/functionobject "cpp/named req/FunctionObject") of a [literal](../../named_req/literaltype "cpp/named req/LiteralType") [`semiregular`](../../concepts/semiregular "cpp/concepts/semiregular") class type. For exposition purposes, the cv-unqualified version of its type is denoted as `*\_\_compare\_weak\_order\_fallback\_fn*`. All instances of `*\_\_compare\_weak\_order\_fallback\_fn*` are equal. The effects of invoking different instances of type `*\_\_compare\_weak\_order\_fallback\_fn*` on the same arguments are equivalent, regardless of whether the expression denoting the instance is an lvalue or rvalue, and is const-qualified or not (however, a volatile-qualified instance is not required to be invocable). Thus, `std::compare_weak_order_fallback` can be copied freely and its copies can be used interchangeably. Given a set of types `Args...`, if `[std::declval](http://en.cppreference.com/w/cpp/utility/declval)<Args>()...` meet the requirements for arguments to `std::compare_weak_order_fallback` above, `*\_\_compare\_weak\_order\_fallback\_fn*` models . * `[std::invocable](http://en.cppreference.com/w/cpp/concepts/invocable)<__compare_weak_order_fallback_fn, Args...>`, * `[std::invocable](http://en.cppreference.com/w/cpp/concepts/invocable)<const __compare_weak_order_fallback_fn, Args...>`, * `[std::invocable](http://en.cppreference.com/w/cpp/concepts/invocable)<__compare_weak_order_fallback_fn&, Args...>`, and * `[std::invocable](http://en.cppreference.com/w/cpp/concepts/invocable)<const __compare_weak_order_fallback_fn&, Args...>`. Otherwise, no function call operator of `*\_\_compare\_weak\_order\_fallback\_fn*` participates in overload resolution. ### Example ``` #include <iostream> #include <compare> // does not support <=> struct Rational_1 { int num; int den; // > 0 }; inline constexpr bool operator<(Rational_1 lhs, Rational_1 rhs) { return lhs.num * rhs.den < rhs.num * lhs.den; } inline constexpr bool operator==(Rational_1 lhs, Rational_1 rhs) { return lhs.num * rhs.den == rhs.num * lhs.den; } // supports <=> struct Rational_2 { int num; int den; // > 0 bool operator==(Rational_2 const&) const = default; }; inline constexpr std::weak_ordering operator<=>(Rational_2 lhs, Rational_2 rhs) { return lhs.num * rhs.den <=> rhs.num * lhs.den; } void print(std::weak_ordering value) { if (value == 0) std::cout << "equal\n"; else if (value < 0) std::cout << "less\n"; else std::cout << "greater\n"; } int main() { Rational_1 a{1, 2}; Rational_1 b{3, 4}; // print(a <=> b); // doesn't work print(std::compare_weak_order_fallback(a, b)); // works, defaults to < and == Rational_2 c{6, 5}; Rational_2 d{8, 7}; print(c <=> d); // works print(std::compare_weak_order_fallback(c, d)); // works } ``` Output: ``` less greater greater ``` ### See also | | | | --- | --- | | [weak\_order](weak_order "cpp/utility/compare/weak order") (C++20) | performs 3-way comparison and produces a result of type `std::weak_ordering` (customization point object) | cpp std::weak_ordering std::weak\_ordering =================== | Defined in header `[<compare>](../../header/compare "cpp/header/compare")` | | | | --- | --- | --- | | ``` class weak_ordering; ``` | | (since C++20) | The class type `std::weak_ordering` is the result type of a [three-way comparison](../../language/operator_comparison#Three-way_comparison "cpp/language/operator comparison") that. * admits all six relational operators (==, !=, <, <=, >, >=) * does not imply substitutability: if a is equivalent to b, f(a) may not be equivalent to f(b), where f denotes a function that reads only comparison-salient state that is accessible via the argument's public const members. In other words, equivalent values may be distinguishable. * does not allow incomparable values: exactly one of a < b, a == b, or a > b must be true ### Constants The type `std::weak_ordering` has three valid values, implemented as const static data members of its type: | Member constant | Definition | | --- | --- | | less(inline constexpr) [static] | a valid value of the type `std::weak_ordering` indicating less-than (ordered before) relationship (public static member constant) | | equivalent(inline constexpr) [static] | a valid value of the type `std::weak_ordering` indicating equivalence (neither ordered before nor ordered after) (public static member constant) | | greater(inline constexpr) [static] | a valid value of the type `std::weak_ordering` indicating greater-than (ordered after) relationship (public static member constant) | ### Conversions `std::weak_ordering` is implicitly-convertible to `std::partial_ordering`, while `std::strong_ordering` is implicitly-convertible to `weak_ordering`. | | | | --- | --- | | **operator partial\_ordering** | implicit conversion to `std::partial_ordering` (public member function) | std::weak\_ordering::operator partial\_ordering ------------------------------------------------ | | | | | --- | --- | --- | | ``` constexpr operator partial_ordering() const noexcept; ``` | | | ### Return value `std::partial_ordering::less` if `v` is `less`, `std::partial_ordering::greater` if `v` is `greater`, `std::partial_ordering::equivalent` if `v` is `equivalent`. ### Comparisons Comparison operators are defined between values of this type and literal `​0​`. This supports the expressions `a <=> b == 0` or `a <=> b < 0` that can be used to convert the result of a three-way comparison operator to a boolean relationship; see [`std::is_eq`](named_comparison_functions "cpp/utility/compare/named comparison functions"), [`std::is_lt`](named_comparison_functions "cpp/utility/compare/named comparison functions"), etc. These functions are not visible to ordinary [unqualified](../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../language/adl "cpp/language/adl") when `std::weak_ordering` is an associated class of the arguments. The behavior of a program that attempts to compare a `weak_ordering` with anything other than the integer literal `​0​` is undefined. | | | | --- | --- | | **operator==operator<operator>operator<=operator>=operator<=>** | compares with zero or a `weak_ordering` (function) | operator== ----------- | | | | | --- | --- | --- | | ``` friend constexpr bool operator==(weak_ordering v, /*unspecified*/ u) noexcept; ``` | (1) | | | ``` friend constexpr bool operator==(weak_ordering v, weak_ordering w) noexcept = default; ``` | (2) | | ### Parameters | | | | | --- | --- | --- | | v, w | - | `std::weak_ordering` values to check | | u | - | an unused parameter of any type that accepts literal zero argument | ### Return value 1) `true` if `v` is `equivalent`, `false` if `v` is `less` or `greater` 2) `true` if both parameters hold the same value, `false` otherwise operator< ---------- | | | | | --- | --- | --- | | ``` friend constexpr bool operator<(weak_ordering v, /*unspecified*/ u) noexcept; ``` | (1) | | | ``` friend constexpr bool operator<(/*unspecified*/ u, weak_ordering v) noexcept; ``` | (2) | | ### Parameters | | | | | --- | --- | --- | | v | - | a `std::weak_ordering` value to check | | u | - | an unused parameter of any type that accepts literal zero argument | ### Return value 1) `true` if `v` is `less`, and `false` if `v` is `greater` or `equivalent` 2) `true` if `v` is `greater`, and `false` if `v` is `less` or `equivalent` operator<= ----------- | | | | | --- | --- | --- | | ``` friend constexpr bool operator<=(weak_ordering v, /*unspecified*/ u) noexcept; ``` | (1) | | | ``` friend constexpr bool operator<=(/*unspecified*/ u, weak_ordering v) noexcept; ``` | (2) | | ### Parameters | | | | | --- | --- | --- | | v | - | a `std::weak_ordering` value to check | | u | - | an unused parameter of any type that accepts literal zero argument | ### Return value 1) `true` if `v` is `less` or `equivalent`, and `false` if `v` is `greater` 2) `true` if `v` is `greater` or `equivalent`, and `false` if `v` is `less` operator> ---------- | | | | | --- | --- | --- | | ``` friend constexpr bool operator>(weak_ordering v, /*unspecified*/ u) noexcept; ``` | (1) | | | ``` friend constexpr bool operator>(/*unspecified*/ u, weak_ordering v) noexcept; ``` | (2) | | ### Parameters | | | | | --- | --- | --- | | v | - | a `std::weak_ordering` value to check | | u | - | an unused parameter of any type that accepts literal zero argument | ### Return value 1) `true` if `v` is `greater`, and `false` if `v` is `less` or `equivalent` 2) `true` if `v` is `less`, and `false` if `v` is `greater` or `equivalent` operator>= ----------- | | | | | --- | --- | --- | | ``` friend constexpr bool operator>=(weak_ordering v, /*unspecified*/ u) noexcept; ``` | (1) | | | ``` friend constexpr bool operator>=(/*unspecified*/ u, weak_ordering v) noexcept; ``` | (2) | | ### Parameters | | | | | --- | --- | --- | | v | - | a `std::weak_ordering` value to check | | u | - | an unused parameter of any type that accepts literal zero argument | ### Return value 1) `true` if `v` is `greater` or `equivalent`, and `false` if `v` is `less` 2) `true` if `v` is `less` or `equivalent`, and `false` if `v` is `greater` operator<=> ------------ | | | | | --- | --- | --- | | ``` friend constexpr weak_ordering operator<=>(weak_ordering v, /*unspecified*/ u) noexcept; ``` | (1) | | | ``` friend constexpr weak_ordering operator<=>(/*unspecified*/ u, weak_ordering v) noexcept; ``` | (2) | | ### Parameters | | | | | --- | --- | --- | | v | - | a `std::weak_ordering` value to check | | u | - | an unused parameter of any type that accepts literal zero argument | ### Return value 1) `v`. 2) `greater` if `v` is `less`, `less` if `v` is `greater`, otherwise `v`. ### Example ### See also | | | | --- | --- | | [strong\_ordering](strong_ordering "cpp/utility/compare/strong ordering") (C++20) | the result type of 3-way comparison that supports all 6 operators and is substitutable (class) | | [partial\_ordering](partial_ordering "cpp/utility/compare/partial ordering") (C++20) | the result type of 3-way comparison that supports all 6 operators, is not substitutable, and allows incomparable values (class) | cpp std::partial_order std::partial\_order =================== | Defined in header `[<compare>](../../header/compare "cpp/header/compare")` | | | | --- | --- | --- | | ``` inline namespace /* unspecified */ { inline constexpr /* unspecified */ partial_order = /* unspecified */; } ``` | | (since C++20) | | Call signature | | | | ``` template< class T, class U > requires /* see below */ constexpr std::partial_ordering partial_order(T&& t, U&& u) noexcept(/* see below */); ``` | | | Compares two values using 3-way comparison and produces a result of type `std::partial_ordering`. Let `t` and `u` be expressions and `T` and `U` denote `decltype((t))` and `decltype((u))` respectively, `std::partial_order(t, u)` is expression-equivalent to: * If `[std::is\_same\_v](http://en.cppreference.com/w/cpp/types/is_same)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<T>, [std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<U>>` is `true`: + `[std::partial\_ordering](http://en.cppreference.com/w/cpp/utility/compare/partial_ordering)(partial_order(t, u))`, if it is a well-formed expression with overload resolution performed in a context that does not include a declaration of `std::partial_order`, + otherwise, `[std::partial\_ordering](http://en.cppreference.com/w/cpp/utility/compare/partial_ordering)([std::compare\_three\_way](http://en.cppreference.com/w/cpp/utility/compare/compare_three_way)()(t, u))`, if it is well-formed, + otherwise, `[std::partial\_ordering](http://en.cppreference.com/w/cpp/utility/compare/partial_ordering)([std::weak\_order](http://en.cppreference.com/w/cpp/utility/compare/weak_order)(t, u))`, if it is well-formed, * In all other cases, the expression is ill-formed, which can result in [substitution failure](../../language/sfinae "cpp/language/sfinae") when it appears in the immediate context of a template instantiation. ### Expression-equivalent Expression `e` is *expression-equivalent* to expression `f`, if. * `e` and `f` have the same effects, and * either both are [constant subexpressions](../../language/constant_expression "cpp/language/constant expression") or else neither is a constant subexpression, and * either both are [potentially-throwing](../../language/noexcept_spec "cpp/language/noexcept spec") or else neither is potentially-throwing (i.e. `noexcept(e) == noexcept(f)`). ### Customization point objects The name `std::partial_order` denotes a *customization point object*, which is a const [function object](../../named_req/functionobject "cpp/named req/FunctionObject") of a [literal](../../named_req/literaltype "cpp/named req/LiteralType") [`semiregular`](../../concepts/semiregular "cpp/concepts/semiregular") class type. For exposition purposes, the cv-unqualified version of its type is denoted as `*\_\_partial\_order\_fn*`. All instances of `*\_\_partial\_order\_fn*` are equal. The effects of invoking different instances of type `*\_\_partial\_order\_fn*` on the same arguments are equivalent, regardless of whether the expression denoting the instance is an lvalue or rvalue, and is const-qualified or not (however, a volatile-qualified instance is not required to be invocable). Thus, `std::partial_order` can be copied freely and its copies can be used interchangeably. Given a set of types `Args...`, if `[std::declval](http://en.cppreference.com/w/cpp/utility/declval)<Args>()...` meet the requirements for arguments to `std::partial_order` above, `*\_\_partial\_order\_fn*` models . * `[std::invocable](http://en.cppreference.com/w/cpp/concepts/invocable)<__partial_order_fn, Args...>`, * `[std::invocable](http://en.cppreference.com/w/cpp/concepts/invocable)<const __partial_order_fn, Args...>`, * `[std::invocable](http://en.cppreference.com/w/cpp/concepts/invocable)<__partial_order_fn&, Args...>`, and * `[std::invocable](http://en.cppreference.com/w/cpp/concepts/invocable)<const __partial_order_fn&, Args...>`. Otherwise, no function call operator of `*\_\_partial\_order\_fn*` participates in overload resolution. ### Notes ### Example ### See also | | | | --- | --- | | [partial\_ordering](partial_ordering "cpp/utility/compare/partial ordering") (C++20) | the result type of 3-way comparison that supports all 6 operators, is not substitutable, and allows incomparable values (class) | | [strong\_order](strong_order "cpp/utility/compare/strong order") (C++20) | performs 3-way comparison and produces a result of type `std::strong_ordering` (customization point object) | | [weak\_order](weak_order "cpp/utility/compare/weak order") (C++20) | performs 3-way comparison and produces a result of type `std::weak_ordering` (customization point object) | | [compare\_partial\_order\_fallback](compare_partial_order_fallback "cpp/utility/compare/compare partial order fallback") (C++20) | performs 3-way comparison and produces a result of type `std::partial_ordering`, even if `operator<=>` is unavailable (customization point object) |
programming_docs
cpp std::compare_strong_order_fallback std::compare\_strong\_order\_fallback ===================================== | Defined in header `[<compare>](../../header/compare "cpp/header/compare")` | | | | --- | --- | --- | | ``` inline namespace /* unspecified */ { inline constexpr /* unspecified */ compare_strong_order_fallback = /* unspecified */; } ``` | | (since C++20) | | Call signature | | | | ``` template< class T, class U > requires /* see below */ constexpr std::strong_ordering compare_strong_order_fallback(T&& t, U&& u) noexcept(/* see below */); ``` | | | Performs three-way comparison on `t` and `u` and produces a result of type `std::strong_ordering`, even if the operator `<=>` is unavailable. Let `t` and `u` be expressions and `T` and `U` denote `decltype((t))` and `decltype((u))` respectively, `std::compare_strong_order_fallback(t, u)` is expression-equivalent to: * If `[std::is\_same\_v](http://en.cppreference.com/w/cpp/types/is_same)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<T>, [std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<U>>` is `true`: + `[std::strong\_order](http://en.cppreference.com/w/cpp/utility/compare/strong_order)(t, u)`, if it is a well-formed expression; + otherwise, ``` t == u ? std::strong_ordering::equal : t < u ? std::strong_ordering::less : std::strong_ordering::greater ``` if `t == u` and `t < u` are both well-formed and convertible to `bool`, except that `t` and `u` are evaluated only once. * In all other cases, `std::compare_strong_order_fallback(t, u)` is ill-formed, which can result in [substitution failure](../../language/sfinae "cpp/language/sfinae") when it appears in the immediate context of a template instantiation. ### Expression-equivalent Expression `e` is *expression-equivalent* to expression `f`, if. * `e` and `f` have the same effects, and * either both are [constant subexpressions](../../language/constant_expression "cpp/language/constant expression") or else neither is a constant subexpression, and * either both are [potentially-throwing](../../language/noexcept_spec "cpp/language/noexcept spec") or else neither is potentially-throwing (i.e. `noexcept(e) == noexcept(f)`). ### Customization point objects The name `std::compare_strong_order_fallback` denotes a *customization point object*, which is a const [function object](../../named_req/functionobject "cpp/named req/FunctionObject") of a [literal](../../named_req/literaltype "cpp/named req/LiteralType") [`semiregular`](../../concepts/semiregular "cpp/concepts/semiregular") class type. For exposition purposes, the cv-unqualified version of its type is denoted as `*\_\_compare\_strong\_order\_fallback\_fn*`. All instances of `*\_\_compare\_strong\_order\_fallback\_fn*` are equal. The effects of invoking different instances of type `*\_\_compare\_strong\_order\_fallback\_fn*` on the same arguments are equivalent, regardless of whether the expression denoting the instance is an lvalue or rvalue, and is const-qualified or not (however, a volatile-qualified instance is not required to be invocable). Thus, `std::compare_strong_order_fallback` can be copied freely and its copies can be used interchangeably. Given a set of types `Args...`, if `[std::declval](http://en.cppreference.com/w/cpp/utility/declval)<Args>()...` meet the requirements for arguments to `std::compare_strong_order_fallback` above, `*\_\_compare\_strong\_order\_fallback\_fn*` models . * `[std::invocable](http://en.cppreference.com/w/cpp/concepts/invocable)<__compare_strong_order_fallback_fn, Args...>`, * `[std::invocable](http://en.cppreference.com/w/cpp/concepts/invocable)<const __compare_strong_order_fallback_fn, Args...>`, * `[std::invocable](http://en.cppreference.com/w/cpp/concepts/invocable)<__compare_strong_order_fallback_fn&, Args...>`, and * `[std::invocable](http://en.cppreference.com/w/cpp/concepts/invocable)<const __compare_strong_order_fallback_fn&, Args...>`. Otherwise, no function call operator of `*\_\_compare\_strong\_order\_fallback\_fn*` participates in overload resolution. ### Example ### See also | | | | --- | --- | | [strong\_order](strong_order "cpp/utility/compare/strong order") (C++20) | performs 3-way comparison and produces a result of type `std::strong_ordering` (customization point object) | cpp std::partial_ordering std::partial\_ordering ====================== | Defined in header `[<compare>](../../header/compare "cpp/header/compare")` | | | | --- | --- | --- | | ``` class partial_ordering; ``` | | (since C++20) | The class type `std::partial_ordering` is the result type of a [three-way comparison](../../language/operator_comparison#Three-way_comparison "cpp/language/operator comparison") that. * admits all six relational operators (==, !=, <, <=, >, >=) * does not imply substitutability: if a is equivalent to b, f(a) may not be equivalent to f(b), where f denotes a function that reads only comparison-salient state that is accessible via the argument's public const members. In other words, equivalent values may be distinguishable. * admits incomparable values: a < b, a == b, and a > b may all be false ### Constants The type `std::partial_ordering` has four valid values, implemented as const static data members of its type: | Member constant | Definition | | --- | --- | | less(inline constexpr) [static] | a valid value of the type `std::partial_ordering` indicating less-than (ordered before) relationship (public static member constant) | | equivalent(inline constexpr) [static] | a valid value of the type `std::partial_ordering` indicating equivalence (neither ordered before nor ordered after) (public static member constant) | | greater(inline constexpr) [static] | a valid value of the type `std::partial_ordering` indicating greater-than (ordered after) relationship (public static member constant) | | unordered(inline constexpr) [static] | a valid value of the type `std::partial_ordering` indicating relationship with an incomparable value (public static member constant) | ### Conversions `std::partial_ordering` cannot be implicitly converted to other comparison category types, while both `std::strong_ordering` and `std::weak_ordering` are implicitly-convertible to `partial_ordering`. ### Comparisons Comparison operators are defined between values of this type and literal `​0​`. This supports the expressions `a <=> b == 0` or `a <=> b < 0` that can be used to convert the result of a three-way comparison operator to a boolean relationship; see [`std::is_eq`](named_comparison_functions "cpp/utility/compare/named comparison functions"), [`std::is_lt`](named_comparison_functions "cpp/utility/compare/named comparison functions"), etc. These functions are not visible to ordinary [unqualified](../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../language/adl "cpp/language/adl") when `std::partial_ordering` is an associated class of the arguments. The behavior of a program that attempts to compare a `partial_ordering` with anything other than the integer literal `​0​` is undefined. | | | | --- | --- | | **operator==operator<operator>operator<=operator>=operator<=>** | compares with zero or a `partial_ordering` (function) | operator== ----------- | | | | | --- | --- | --- | | ``` friend constexpr bool operator==( partial_ordering v, /*unspecified*/ u ) noexcept; ``` | (1) | | | ``` friend constexpr bool operator==( partial_ordering v, partial_ordering w ) noexcept = default; ``` | (2) | | ### Parameters | | | | | --- | --- | --- | | v, w | - | `std::partial_ordering` values to check | | u | - | an unused parameter of any type that accepts literal zero argument | ### Return value 1) `true` if `v` is `equivalent`, `false` if `v` is `less`, `greater`, or `unordered` 2) `true` if both parameters hold the same value, `false` otherwise operator< ---------- | | | | | --- | --- | --- | | ``` friend constexpr bool operator<( partial_ordering v, /*unspecified*/ u ) noexcept; ``` | (1) | | | ``` friend constexpr bool operator<( /*unspecified*/ u, partial_ordering v ) noexcept; ``` | (2) | | ### Parameters | | | | | --- | --- | --- | | v | - | a `std::partial_ordering` value to check | | u | - | an unused parameter of any type that accepts literal zero argument | ### Return value 1) `true` if `v` is `less`, and `false` if `v` is `greater`, `equivalent`, or `unordered` 2) `true` if `v` is `greater`, and `false` if `v` is `less`, `equivalent`, or `unordered` operator<= ----------- | | | | | --- | --- | --- | | ``` friend constexpr bool operator<=( partial_ordering v, /*unspecified*/ u ) noexcept; ``` | (1) | | | ``` friend constexpr bool operator<=( /*unspecified*/ u, partial_ordering v ) noexcept; ``` | (2) | | ### Parameters | | | | | --- | --- | --- | | v | - | a `std::partial_ordering` value to check | | u | - | an unused parameter of any type that accepts literal zero argument | ### Return value 1) `true` if `v` is `less` or `equivalent`, and `false` if `v` is `greater` or `unordered` 2) `true` if `v` is `greater` or `equivalent`, and `false` if `v` is `less` or `unordered` operator> ---------- | | | | | --- | --- | --- | | ``` friend constexpr bool operator>( partial_ordering v, /*unspecified*/ u ) noexcept; ``` | (1) | | | ``` friend constexpr bool operator>( /*unspecified*/ u, partial_ordering v ) noexcept; ``` | (2) | | ### Parameters | | | | | --- | --- | --- | | v | - | a `std::partial_ordering` value to check | | u | - | an unused parameter of any type that accepts literal zero argument | ### Return value 1) `true` if `v` is `greater`, and `false` if `v` is `less`, `equivalent`, or `unordered` 2) `true` if `v` is `less`, and `false` if `v` is `greater`, `equivalent`, or `unordered` operator>= ----------- | | | | | --- | --- | --- | | ``` friend constexpr bool operator>=( partial_ordering v, /*unspecified*/ u ) noexcept; ``` | (1) | | | ``` friend constexpr bool operator>=( /*unspecified*/ u, partial_ordering v ) noexcept; ``` | (2) | | ### Parameters | | | | | --- | --- | --- | | v | - | a `std::partial_ordering` value to check | | u | - | an unused parameter of any type that accepts literal zero argument | ### Return value 1) `true` if `v` is `greater` or `equivalent`, and `false` if `v` is `less` or `unordered` 2) `true` if `v` is `less` or `equivalent`, and `false` if `v` is `greater` or `unordered` operator<=> ------------ | | | | | --- | --- | --- | | ``` friend constexpr partial_ordering operator<=>( partial_ordering v, /*unspecified*/ u ) noexcept; ``` | (1) | | | ``` friend constexpr partial_ordering operator<=>( /*unspecified*/ u, partial_ordering v ) noexcept; ``` | (2) | | ### Parameters | | | | | --- | --- | --- | | v | - | a `std::partial_ordering` value to check | | u | - | an unused parameter of any type that accepts literal zero argument | ### Return value 1) `v`. 2) `greater` if `v` is `less`, `less` if `v` is `greater`, otherwise `v`. ### Notes The [built-in `operator<=>`](../../language/operator_comparison#Three-way_comparison "cpp/language/operator comparison") between floating-point values uses this ordering: the positive zero and the negative zero compare `equivalent`, but can be distinguished, and NaN values compare `unordered` with any other value. ### Example ### See also | | | | --- | --- | | [strong\_ordering](strong_ordering "cpp/utility/compare/strong ordering") (C++20) | the result type of 3-way comparison that supports all 6 operators and is substitutable (class) | | [weak\_ordering](weak_ordering "cpp/utility/compare/weak ordering") (C++20) | the result type of 3-way comparison that supports all 6 operators and is not substitutable (class) | cpp std::compare_partial_order_fallback std::compare\_partial\_order\_fallback ====================================== | Defined in header `[<compare>](../../header/compare "cpp/header/compare")` | | | | --- | --- | --- | | ``` inline namespace /* unspecified */ { inline constexpr /* unspecified */ compare_partial_order_fallback = /* unspecified */; } ``` | | (since C++20) | | Call signature | | | | ``` template< class T, class U > requires /* see below */ constexpr std::partial_ordering compare_partial_order_fallback(T&& t, U&& u) noexcept(/* see below */); ``` | | | Performs three-way comparison on `t` and `u` and produces a result of type `std::partial_ordering`, even if the operator `<=>` is unavailable. Let `t` and `u` be expressions and `T` and `U` denote `decltype((t))` and `decltype((u))` respectively, `std::compare_partial_order_fallback(t, u)` is expression-equivalent to: * If `[std::is\_same\_v](http://en.cppreference.com/w/cpp/types/is_same)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<T>, [std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<U>>` is `true`: + `[std::partial\_order](http://en.cppreference.com/w/cpp/utility/compare/partial_order)(t, u)`, if it is a well-formed expression; + otherwise, ``` t == u ? std::partial_ordering::equivalent : t < u ? std::partial_ordering::less : u < t ? std::partial_ordering::greater : std::partial_ordering::unordered ``` if `t == u`, `t < u`, and `u < t` are all well-formed and convertible to `bool`, except that `t` and `u` are evaluated only once. * In all other cases, `std::compare_partial_order_fallback(t, u)` is ill-formed, which can result in [substitution failure](../../language/sfinae "cpp/language/sfinae") when it appears in the immediate context of a template instantiation. ### Expression-equivalent Expression `e` is *expression-equivalent* to expression `f`, if. * `e` and `f` have the same effects, and * either both are [constant subexpressions](../../language/constant_expression "cpp/language/constant expression") or else neither is a constant subexpression, and * either both are [potentially-throwing](../../language/noexcept_spec "cpp/language/noexcept spec") or else neither is potentially-throwing (i.e. `noexcept(e) == noexcept(f)`). ### Customization point objects The name `std::compare_partial_order_fallback` denotes a *customization point object*, which is a const [function object](../../named_req/functionobject "cpp/named req/FunctionObject") of a [literal](../../named_req/literaltype "cpp/named req/LiteralType") [`semiregular`](../../concepts/semiregular "cpp/concepts/semiregular") class type. For exposition purposes, the cv-unqualified version of its type is denoted as `*\_\_compare\_partial\_order\_fallback\_fn*`. All instances of `*\_\_compare\_partial\_order\_fallback\_fn*` are equal. The effects of invoking different instances of type `*\_\_compare\_partial\_order\_fallback\_fn*` on the same arguments are equivalent, regardless of whether the expression denoting the instance is an lvalue or rvalue, and is const-qualified or not (however, a volatile-qualified instance is not required to be invocable). Thus, `std::compare_partial_order_fallback` can be copied freely and its copies can be used interchangeably. Given a set of types `Args...`, if `[std::declval](http://en.cppreference.com/w/cpp/utility/declval)<Args>()...` meet the requirements for arguments to `std::compare_partial_order_fallback` above, `*\_\_compare\_partial\_order\_fallback\_fn*` models . * `[std::invocable](http://en.cppreference.com/w/cpp/concepts/invocable)<__compare_partial_order_fallback_fn, Args...>`, * `[std::invocable](http://en.cppreference.com/w/cpp/concepts/invocable)<const __compare_partial_order_fallback_fn, Args...>`, * `[std::invocable](http://en.cppreference.com/w/cpp/concepts/invocable)<__compare_partial_order_fallback_fn&, Args...>`, and * `[std::invocable](http://en.cppreference.com/w/cpp/concepts/invocable)<const __compare_partial_order_fallback_fn&, Args...>`. Otherwise, no function call operator of `*\_\_compare\_partial\_order\_fallback\_fn*` participates in overload resolution. ### Example ### See also | | | | --- | --- | | [partial\_order](partial_order "cpp/utility/compare/partial order") (C++20) | performs 3-way comparison and produces a result of type `std::partial_ordering` (customization point object) | cpp std::is_eq, std::is_neq, std::is_lt, std::is_gt, std::is_lteq, std::is_gteq std::is\_eq, std::is\_neq, std::is\_lt, std::is\_gt, std::is\_lteq, std::is\_gteq ================================================================================= | Defined in header `[<compare>](../../header/compare "cpp/header/compare")` | | | | --- | --- | --- | | ``` constexpr bool is_eq( std::partial_ordering cmp ) noexcept; ``` | (1) | (since C++20) | | ``` constexpr bool is_neq( std::partial_ordering cmp ) noexcept; ``` | (2) | (since C++20) | | ``` constexpr bool is_lt( std::partial_ordering cmp ) noexcept; ``` | (3) | (since C++20) | | ``` constexpr bool is_lteq( std::partial_ordering cmp ) noexcept; ``` | (4) | (since C++20) | | ``` constexpr bool is_gt( std::partial_ordering cmp ) noexcept; ``` | (5) | (since C++20) | | ``` constexpr bool is_gteq( std::partial_ordering cmp ) noexcept ``` | (6) | (since C++20) | These functions take a result of 3-way comparison and convert it to the result of one of the six relational operators. Specifically, these functions return. 1) `cmp == 0` 2) `cmp != 0` 3) `cmp < 0` 4) `cmp <= 0` 5) `cmp > 0` 6) `cmp >= 0` ### Parameters | | | | | --- | --- | --- | | cmp | - | result of 3-way comparison | ### Return value `bool` result of the corresponding relational operation. ### Example ### See also | | | | --- | --- | | [partial\_ordering](partial_ordering "cpp/utility/compare/partial ordering") (C++20) | the result type of 3-way comparison that supports all 6 operators, is not substitutable, and allows incomparable values (class) | cpp std::common_comparison_category std::common\_comparison\_category ================================= | Defined in header `[<compare>](../../header/compare "cpp/header/compare")` | | | | --- | --- | --- | | ``` template<class... Ts> struct common_comparison_category { using type = /*see below*/ ; }; ``` | | (since C++20) | The class template `std::common_comparison_category` provides an alias (as the member typedef `type`) for the strongest comparison category to which all of the template arguments `Ts...` can be converted. In detail, the common comparison type of a list of n types T0...Tn-1 is defined as follows: * If any Ti is not a comparison category type ([`std::partial_ordering`](partial_ordering "cpp/utility/compare/partial ordering"), [`std::weak_ordering`](weak_ordering "cpp/utility/compare/weak ordering"), [`std::strong_ordering`](strong_ordering "cpp/utility/compare/strong ordering")), U is `void`. * Otherwise, if at least one Ti is [`std::partial_ordering`](partial_ordering "cpp/utility/compare/partial ordering"), U is [`std::partial_ordering`](partial_ordering "cpp/utility/compare/partial ordering") * Otherwise, if at least one Ti is [`std::weak_ordering`](weak_ordering "cpp/utility/compare/weak ordering"), U is [`std::weak_ordering`](weak_ordering "cpp/utility/compare/weak ordering") * Otherwise (if every Ti is [`std::strong_ordering`](strong_ordering "cpp/utility/compare/strong ordering"), or if the list is empty), U is [`std::strong_ordering`](strong_ordering "cpp/utility/compare/strong ordering"). ### Template parameters | | | | | --- | --- | --- | | ...Ts | - | a possibly empty list of types | ### Helper template | | | | | --- | --- | --- | | ``` template< class... Ts > using common_comparison_category_t = typename common_comparison_category<Ts...>::type; ``` | | (since C++20) | ### Member types | Member type | Definition | | --- | --- | | `type` | the strongest common comparison category (as defined above) | ### Possible implementation | | | --- | | ``` namespace detail { template<unsigned int> struct common_cmpcat_base { using type = void; }; template<> struct common_cmpcat_base<0u> { using type = std::strong_ordering; }; template<> struct common_cmpcat_base<2u> { using type = std::partial_ordering; }; template<> struct common_cmpcat_base<4u> { using type = std::weak_ordering; }; template<> struct common_cmpcat_base<6u> { using type = std::partial_ordering; }; } // namespace detail template<class...Ts> struct common_comparison_category : detail::common_cmpcat_base<(0u | ... | (std::is_same_v<Ts, std::strong_ordering> ? 0u : std::is_same_v<Ts, std::weak_ordering> ? 4u : std::is_same_v<Ts, std::partial_ordering> ? 2u : 1u) )> {}; ``` | ### Example ### See also | | | | --- | --- | | [strong\_ordering](strong_ordering "cpp/utility/compare/strong ordering") (C++20) | the result type of 3-way comparison that supports all 6 operators and is substitutable (class) | | [weak\_ordering](weak_ordering "cpp/utility/compare/weak ordering") (C++20) | the result type of 3-way comparison that supports all 6 operators and is not substitutable (class) | | [partial\_ordering](partial_ordering "cpp/utility/compare/partial ordering") (C++20) | the result type of 3-way comparison that supports all 6 operators, is not substitutable, and allows incomparable values (class) |
programming_docs
cpp std::strong_order std::strong\_order ================== | Defined in header `[<compare>](../../header/compare "cpp/header/compare")` | | | | --- | --- | --- | | ``` inline namespace /* unspecified */ { inline constexpr /* unspecified */ strong_order = /* unspecified */; } ``` | | (since C++20) | | Call signature | | | | ``` template< class T, class U > requires /* see below */ constexpr std::strong_ordering strong_order( T&& t, U&& u ) noexcept(/* see below */); ``` | | | Compares two values using 3-way comparison and produces a result of type `std::strong_ordering`. Let `t` and `u` be expressions and `T` and `U` denote `decltype((t))` and `decltype((u))` respectively, `std::strong_order(t, u)` is expression-equivalent to: * If `[std::is\_same\_v](http://en.cppreference.com/w/cpp/types/is_same)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<T>, [std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<U>>` is `true`: + `[std::strong\_ordering](http://en.cppreference.com/w/cpp/utility/compare/strong_ordering)(strong_order(t, u))`, if it is a well-formed expression with overload resolution performed in a context that does not include a declaration of `std::strong_order`, + otherwise, if `T` is a floating-point type: - if `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<T>::is\_iec559` is `true`, performs the ISO/IEC/IEEE 60559 *totalOrder* comparison of floating-point values and returns that result as a value of type `std::strong_ordering` (note: this comparison can distinguish between the positive and negative zero and between the NaNs with different representations), - otherwise, yields a value of type `std::strong_ordering` that is consistent with the ordering observed by `T`'s comparison operators, + otherwise, `[std::strong\_ordering](http://en.cppreference.com/w/cpp/utility/compare/strong_ordering)([std::compare\_three\_way](http://en.cppreference.com/w/cpp/utility/compare/compare_three_way)()(t, u))` if it is well-formed. * In all other cases, the expression is ill-formed, which can result in [substitution failure](../../language/sfinae "cpp/language/sfinae") when it appears in the immediate context of a template instantiation. ### Expression-equivalent Expression `e` is *expression-equivalent* to expression `f`, if. * `e` and `f` have the same effects, and * either both are [constant subexpressions](../../language/constant_expression "cpp/language/constant expression") or else neither is a constant subexpression, and * either both are [potentially-throwing](../../language/noexcept_spec "cpp/language/noexcept spec") or else neither is potentially-throwing (i.e. `noexcept(e) == noexcept(f)`). ### Customization point objects The name `std::strong_order` denotes a *customization point object*, which is a const [function object](../../named_req/functionobject "cpp/named req/FunctionObject") of a [literal](../../named_req/literaltype "cpp/named req/LiteralType") [`semiregular`](../../concepts/semiregular "cpp/concepts/semiregular") class type. For exposition purposes, the cv-unqualified version of its type is denoted as `*\_\_strong\_order\_fn*`. All instances of `*\_\_strong\_order\_fn*` are equal. The effects of invoking different instances of type `*\_\_strong\_order\_fn*` on the same arguments are equivalent, regardless of whether the expression denoting the instance is an lvalue or rvalue, and is const-qualified or not (however, a volatile-qualified instance is not required to be invocable). Thus, `std::strong_order` can be copied freely and its copies can be used interchangeably. Given a set of types `Args...`, if `[std::declval](http://en.cppreference.com/w/cpp/utility/declval)<Args>()...` meet the requirements for arguments to `std::strong_order` above, `*\_\_strong\_order\_fn*` models . * `[std::invocable](http://en.cppreference.com/w/cpp/concepts/invocable)<__strong_order_fn, Args...>`, * `[std::invocable](http://en.cppreference.com/w/cpp/concepts/invocable)<const __strong_order_fn, Args...>`, * `[std::invocable](http://en.cppreference.com/w/cpp/concepts/invocable)<__strong_order_fn&, Args...>`, and * `[std::invocable](http://en.cppreference.com/w/cpp/concepts/invocable)<const __strong_order_fn&, Args...>`. Otherwise, no function call operator of `*\_\_strong\_order\_fn*` participates in overload resolution. ### Notes #### Strict total order of IEEE floating-point types Let `x` and `y` be values of same IEEE floating-point type, and `total_order_less(x, y)` be the boolean result indicating if `x` precedes `y` in the strict total order defined by *totalOrder* in ISO/IEC/IEEE 60559. `(total_order_less(x, y) || total_order_less(y, x)) == false` if and only if `x` and `y` have the same bit pattern. * if neither `x` nor `y` is NaN: + if `x < y`, then `total_order_less(x, y) == true`; + if `x > y`, then `total_order_less(x, y) == false`; + if `x == y`, - if `x` is negative zero and `y` is positive zero, `total_order_less(x, y) == true`, - if `x` is not zero and `x`'s exponent field is less than `y`'s, then `total_order_less(x, y) == (x > 0)` (only meaningful for decimal floating-point number); * if either `x` or `y` is NaN: + if `x` is negative NaN and `y` is not negative NaN, then `total_order_less(x, y) == true`, + if `x` is not positive NaN and `y` is positive NaN, then `total_order_less(x, y) == true`, + if both `x` and `y` are NaNs with the same sign and `x`'s mantissa field is less than `y`'s, then `total_order_less(x, y) == ![std::signbit](http://en.cppreference.com/w/cpp/numeric/math/signbit)(x)`. ### Example ### See also | | | | --- | --- | | [strong\_ordering](strong_ordering "cpp/utility/compare/strong ordering") (C++20) | the result type of 3-way comparison that supports all 6 operators and is substitutable (class) | | [weak\_order](weak_order "cpp/utility/compare/weak order") (C++20) | performs 3-way comparison and produces a result of type `std::weak_ordering` (customization point object) | | [partial\_order](partial_order "cpp/utility/compare/partial order") (C++20) | performs 3-way comparison and produces a result of type `std::partial_ordering` (customization point object) | | [compare\_strong\_order\_fallback](compare_strong_order_fallback "cpp/utility/compare/compare strong order fallback") (C++20) | performs 3-way comparison and produces a result of type `std::strong_ordering`, even if `operator<=>` is unavailable (customization point object) | cpp setjmp setjmp ====== | Defined in header `[<csetjmp>](../../header/csetjmp "cpp/header/csetjmp")` | | | | --- | --- | --- | | ``` #define setjmp(env) /* implementation-defined */ ``` | | | Saves the current execution context into a variable `env` of type `[std::jmp\_buf](jmp_buf "cpp/utility/program/jmp buf")`. This variable can later be used to restore the current execution context by `[std::longjmp](longjmp "cpp/utility/program/longjmp")` function. That is, when a call to `[std::longjmp](longjmp "cpp/utility/program/longjmp")` function is made, the execution continues at the particular call site that constructed the `[std::jmp\_buf](jmp_buf "cpp/utility/program/jmp buf")` variable passed to `[std::longjmp](longjmp "cpp/utility/program/longjmp")`. In that case `setjmp` returns the value passed to `[std::longjmp](longjmp "cpp/utility/program/longjmp")`. The invocation of `setjmp` must appear only in one of the following contexts: * the entire controlling expression of [`if`](../../language/if "cpp/language/if"), [`switch`](../../language/switch "cpp/language/switch"), [`while`](../../language/while "cpp/language/while"), [`do-while`](../../language/do "cpp/language/do"), [`for`](../../language/for "cpp/language/for"). ``` switch(setjmp(env)) { .. ``` * one operand of a relational or equality operator with the other operand an integer constant expression, with the resulting expression being the entire controlling expression of [`if`](../../language/if "cpp/language/if"), [`switch`](../../language/switch "cpp/language/switch"), [`while`](../../language/while "cpp/language/while"), [`do-while`](../../language/do "cpp/language/do"), [`for`](../../language/for "cpp/language/for"). ``` if(setjmp(env) > 0) { ... ``` * the operand of a unary ! operator with the resulting expression being the entire controlling expression of [`if`](../../language/if "cpp/language/if"), [`switch`](../../language/switch "cpp/language/switch"), [`while`](../../language/while "cpp/language/while"), [`do-while`](../../language/do "cpp/language/do"), [`for`](../../language/for "cpp/language/for"). ``` while(!setjmp(env)) { ... ``` * the entire expression of an [expression statement](../../language/statements#Expression_statements "cpp/language/statements") (possibly cast to `void`). ``` setjmp(env); ``` If `setjmp` appears in any other context, the behavior is undefined. Upon return to the scope of `setjmp`, all accessible objects, floating-point status flags, and other components of the abstract machine have the same values as they had when `[std::longjmp](longjmp "cpp/utility/program/longjmp")` was executed, except for the non-[volatile](../../language/cv "cpp/language/cv") local variables in the function containing the invocation of `setjmp`, whose values are indeterminate if they have been changed since the `setjmp` invocation. ### Parameters | | | | | --- | --- | --- | | env | - | variable to save the execution state of the program to. | ### Return value `​0​` if the macro was called by the original code and the execution context was saved to `env`. Non-zero value if a non-local jump was just performed. The return value is the same as passed to `[std::longjmp](longjmp "cpp/utility/program/longjmp")`. ### Notes Above requirements forbid using return value of `setjmp` in data flow (e.g. to initialize or assign an object with it). The return value can only be either used in control flow or discarded. ### Example ``` #include <iostream> #include <csetjmp> std::jmp_buf my_jump_buffer; [[noreturn]] void foo(int count) { std::cout << "foo(" << count << ") called\n"; std::longjmp(my_jump_buffer, count+1); // setjmp() will return count+1 } int main() { volatile int count = 0; // modified locals in setjmp scope must be volatile if (setjmp(my_jump_buffer) != 5) { // equality against constant expression in an if count = count + 1; // ++count, count += 1, etc on 'volatile'-qualified // left operand are deprecated since C++20 (P1152) foo(count); // This will cause setjmp() to exit } } ``` Output: ``` foo(1) called foo(2) called foo(3) called foo(4) called ``` ### See also | | | | --- | --- | | [longjmp](longjmp "cpp/utility/program/longjmp") | jumps to specified location (function) | | [C documentation](https://en.cppreference.com/w/c/program/setjmp "c/program/setjmp") for `setjmp` | cpp SIG_DFL, SIG_IGN SIG\_DFL, SIG\_IGN ================== | Defined in header `[<csignal>](../../header/csignal "cpp/header/csignal")` | | | | --- | --- | --- | | ``` #define SIG_DFL /*implementation defined*/ ``` | | | | ``` #define SIG_IGN /*implementation defined*/ ``` | | | The `SIG_DFL` and `SIG_IGN` macros expand into integral expressions that are not equal to an address of any function. The macros define signal handling strategies for `[std::signal](http://en.cppreference.com/w/cpp/utility/program/signal)()` function. | Constant | Explanation | | --- | --- | | `SIG_DFL` | default signal handling | | `SIG_IGN` | signal is ignored | ### See also | | | --- | | [C documentation](https://en.cppreference.com/w/c/program/SIG_strategies "c/program/SIG strategies") for `SIG_DFL, SIG_IGN` | cpp std::_Exit std::\_Exit =========== | Defined in header `[<cstdlib>](../../header/cstdlib "cpp/header/cstdlib")` | | | | --- | --- | --- | | ``` [[noreturn]] void _Exit( int exit_code ) noexcept; ``` | | (since C++11) | Causes normal program termination to occur without completely cleaning the resources. Destructors of variables with automatic, thread local and static storage durations are not called. Functions passed to `[std::at\_quick\_exit()](at_quick_exit "cpp/utility/program/at quick exit")` or `[std::atexit()](atexit "cpp/utility/program/atexit")` are not called. Whether open resources such as files are closed is implementation defined. If `exit_code` is `0` or `[EXIT\_SUCCESS](exit_status "cpp/utility/program/EXIT status")`, an implementation-defined status indicating successful termination is returned to the host environment. If `exit_code` is `[EXIT\_FAILURE](exit_status "cpp/utility/program/EXIT status")`, an implementation-defined status, indicating *unsuccessful* termination, is returned. In other cases implementation-defined status value is returned. ### Parameters | | | | | --- | --- | --- | | exit\_code | - | exit status of the program | ### Return value (none). ### Example ``` #include <iostream> class Static { public: ~Static() { std::cout << "Static dtor\n"; } }; class Local { public: ~Local() { std::cout << "Local dtor\n"; } }; Static static_variable; // dtor of this object will *not* be called void atexit_handler() { std::cout << "atexit handler\n"; } int main() { Local local_variable; // dtor of this object will *not* be called // handler will *not* be called const int result = std::atexit(atexit_handler); if (result != 0) { std::cerr << "atexit registration failed\n"; return EXIT_FAILURE; } std::cout << "test" << std::endl; // flush from std::endl // needs to be here, otherwise nothing will be printed std::_Exit(EXIT_FAILURE); } ``` Output: ``` test ``` ### See also | | | | --- | --- | | [abort](abort "cpp/utility/program/abort") | causes abnormal program termination (without cleaning up) (function) | | [exit](exit "cpp/utility/program/exit") | causes normal program termination with cleaning up (function) | | [C documentation](https://en.cppreference.com/w/c/program/_Exit "c/program/ Exit") for `_Exit` | cpp std::system std::system =========== | Defined in header `[<cstdlib>](../../header/cstdlib "cpp/header/cstdlib")` | | | | --- | --- | --- | | ``` int system( const char* command ); ``` | | | Calls the host environment's command processor (e.g. `/bin/sh`, `cmd.exe`, `command.com`) with the parameter `command`. Returns an implementation-defined value (usually the value that the invoked program returns). If `command` is a null pointer, checks if the host environment has a command processor and returns a nonzero value if and only if the command processor exists. ### Parameters | | | | | --- | --- | --- | | command | - | character string identifying the command to be run in the command processor. If a null pointer is given, command processor is checked for existence | ### Return value Implementation-defined value. If `command` is a null pointer, returns a nonzero value if and only if the command processor exists. ### Notes On POSIX systems, the return value can be decomposed using [WEXITSTATUS and WSTOPSIG](http://pubs.opengroup.org/onlinepubs/9699919799/functions/wait.html). The related POSIX function [popen](http://pubs.opengroup.org/onlinepubs/9699919799/functions/popen.html) makes the output generated by `command` available to the caller. An explicit flush of `[std::cout](../../io/cout "cpp/io/cout")` is also necessary before a call to `std::system`, if the spawned process performs any screen I/O. ### Example ``` #include <cstdlib> #include <fstream> #include <iostream> int main() { std::system("ls -l >test.txt"); // execute the UNIX command "ls -l >test.txt" std::cout << std::ifstream("test.txt").rdbuf(); } ``` Possible output: ``` total 16 -rwxr-xr-x 1 2001 2000 8859 Sep 30 20:52 a.out -rw-rw-rw- 1 2001 2000 161 Sep 30 20:52 main.cpp -rw-r--r-- 1 2001 2000 0 Sep 30 20:52 test.txt ``` ### See also | | | --- | | [C documentation](https://en.cppreference.com/w/c/program/system "c/program/system") for `system` | cpp SIG_ERR SIG\_ERR ======== | Defined in header `[<csignal>](../../header/csignal "cpp/header/csignal")` | | | | --- | --- | --- | | ``` #define SIG_ERR /* implementation defined */ ``` | | | A value of type `void (*)(int)`. When returned by `[std::signal](signal "cpp/utility/program/signal")`, indicates that an error has occurred. ### See also | | | | --- | --- | | [signal](signal "cpp/utility/program/signal") | sets a signal handler for particular signal (function) | | [C documentation](https://en.cppreference.com/w/c/program/SIG_ERR "c/program/SIG ERR") for `SIG_ERR` | cpp std::abort std::abort ========== | Defined in header `[<cstdlib>](../../header/cstdlib "cpp/header/cstdlib")` | | | | --- | --- | --- | | ``` void abort(); ``` | | (until C++11) | | ``` [[noreturn]] void abort() noexcept; ``` | | (since C++11) | Causes abnormal program termination unless `[SIGABRT](sig_types "cpp/utility/program/SIG types")` is being caught by a signal handler passed to `[std::signal](signal "cpp/utility/program/signal")` and the handler does not return. Destructors of variables with automatic, thread local (since C++11) and static [storage durations](../../language/storage_duration "cpp/language/storage duration") are not called. Functions registered with `[std::atexit()](atexit "cpp/utility/program/atexit")` and `[std::at\_quick\_exit](at_quick_exit "cpp/utility/program/at quick exit")` (since C++11) are also not called. Whether open resources such as files are closed is implementation defined. An implementation defined status is returned to the host environment that indicates unsuccessful execution. ### Parameters (none). ### Return value None because it does not return. ### Exceptions Throws nothing. ### Notes POSIX specifies that the [`abort()`](https://pubs.opengroup.org/onlinepubs/9699919799/functions/abort.html) function overrides blocking or ignoring the `SIGABRT` signal. Some compiler intrinsics, e.g. [`__builtin_trap`](https://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html) (gcc, clang, and icc) or [`__debugbreak`](https://docs.microsoft.com/en-us/cpp/intrinsics/debugbreak) (msvc), can be used to terminate the program as fast as possible. ### Example ``` #include <csignal> #include <iostream> #include <cstdlib> class Tester { public: Tester() { std::cout << "Tester ctor\n"; } ~Tester() { std::cout << "Tester dtor\n"; } }; Tester static_tester; // Destructor not called void signal_handler(int signal) { if (signal == SIGABRT) { std::cerr << "SIGABRT received\n"; } else { std::cerr << "Unexpected signal " << signal << " received\n"; } std::_Exit(EXIT_FAILURE); } int main() { Tester automatic_tester; // Destructor not called // Setup handler auto previous_handler = std::signal(SIGABRT, signal_handler); if (previous_handler == SIG_ERR) { std::cerr << "Setup failed\n"; return EXIT_FAILURE; } std::abort(); // Raise SIGABRT std::cout << "This code is unreachable\n"; } ``` Output: ``` Tester ctor Tester ctor SIGABRT received ``` ### See also | | | | --- | --- | | [exit](exit "cpp/utility/program/exit") | causes normal program termination with cleaning up (function) | | [atexit](atexit "cpp/utility/program/atexit") | registers a function to be called on `[std::exit()](exit "cpp/utility/program/exit")` invocation (function) | | [quick\_exit](quick_exit "cpp/utility/program/quick exit") (C++11) | causes quick program termination without completely cleaning up (function) | | [at\_quick\_exit](at_quick_exit "cpp/utility/program/at quick exit") (C++11) | registers a function to be called on `[std::quick\_exit](quick_exit "cpp/utility/program/quick exit")` invocation (function) | | [signal](signal "cpp/utility/program/signal") | sets a signal handler for particular signal (function) | | [terminate](../../error/terminate "cpp/error/terminate") | function called when exception handling fails (function) | | [C documentation](https://en.cppreference.com/w/c/program/abort "c/program/abort") for `abort` |
programming_docs
cpp std::quick_exit std::quick\_exit ================ | Defined in header `[<cstdlib>](../../header/cstdlib "cpp/header/cstdlib")` | | | | --- | --- | --- | | ``` [[noreturn]] void quick_exit( int exit_code ) noexcept; ``` | | (since C++11) | Causes normal program termination to occur without completely cleaning the resources. Functions passed to `[std::at\_quick\_exit](at_quick_exit "cpp/utility/program/at quick exit")` are called in reverse order of their registration. If an exception tries to propagate out of any of the functions, `[std::terminate](../../error/terminate "cpp/error/terminate")` is called. After calling the registered functions, calls `[std::\_Exit](http://en.cppreference.com/w/cpp/utility/program/_Exit)(exit_code)`. Functions passed to `[std::atexit](atexit "cpp/utility/program/atexit")` are not called. ### Parameters | | | | | --- | --- | --- | | exit\_code | - | exit status of the program | ### Return value (none). ### Example ``` #include <cstdlib> #include <iostream> template <int N> void quick_exit_handler() { std::cout << "quick_exit handler #" << N << std::endl; // flush is intended } void at_exit_handler() { std::cout << "at_exit handler\n"; } int main() { if ( std::at_quick_exit( quick_exit_handler<1> ) or std::at_quick_exit( quick_exit_handler<2> ) ) { std::cerr << "Registration failed\n"; return EXIT_FAILURE; } std::atexit( at_exit_handler ); // the handler will not be called struct R { ~R() { std::cout << "destructor\n"; } } resource; /*...*/ std::quick_exit( EXIT_SUCCESS ); std::cout << "This statement is unreachable...\n"; } ``` Output: ``` quick_exit handler #2 quick_exit handler #1 ``` ### See also | | | | --- | --- | | [abort](abort "cpp/utility/program/abort") | causes abnormal program termination (without cleaning up) (function) | | [exit](exit "cpp/utility/program/exit") | causes normal program termination with cleaning up (function) | | [atexit](atexit "cpp/utility/program/atexit") | registers a function to be called on `[std::exit()](exit "cpp/utility/program/exit")` invocation (function) | | [at\_quick\_exit](at_quick_exit "cpp/utility/program/at quick exit") (C++11) | registers a function to be called on `std::quick_exit` invocation (function) | | [C documentation](https://en.cppreference.com/w/c/program/quick_exit "c/program/quick exit") for `quick_exit` | cpp SIGTERM, SIGSEGV, SIGINT, SIGILL, SIGABRT, SIGFPE SIGTERM, SIGSEGV, SIGINT, SIGILL, SIGABRT, SIGFPE ================================================= | Defined in header `[<csignal>](../../header/csignal "cpp/header/csignal")` | | | | --- | --- | --- | | ``` #define SIGTERM /*implementation defined*/ ``` | | | | ``` #define SIGSEGV /*implementation defined*/ ``` | | | | ``` #define SIGINT /*implementation defined*/ ``` | | | | ``` #define SIGILL /*implementation defined*/ ``` | | | | ``` #define SIGABRT /*implementation defined*/ ``` | | | | ``` #define SIGFPE /*implementation defined*/ ``` | | | Each of the above macro constants expands to an integer constant expression with distinct values, which represent different signals sent to the program. | Constant | Explanation | | --- | --- | | `SIGTERM` | termination request, sent to the program | | `SIGSEGV` | invalid memory access (segmentation fault) | | `SIGINT` | external interrupt, usually initiated by the user | | `SIGILL` | invalid program image, such as invalid instruction | | `SIGABRT` | abnormal termination condition, as is e.g. initiated by `[std::abort()](abort "cpp/utility/program/abort")` | | `SIGFPE` | erroneous arithmetic operation such as divide by zero | ### Notes Additional signal names [are specified by POSIX](http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/signal.h.html). ### See also | | | | --- | --- | | [signal](signal "cpp/utility/program/signal") | sets a signal handler for particular signal (function) | | [raise](raise "cpp/utility/program/raise") | runs the signal handler for particular signal (function) | | [C documentation](https://en.cppreference.com/w/c/program/SIG_types "c/program/SIG types") for signal types | cpp std::longjmp std::longjmp ============ | Defined in header `[<csetjmp>](../../header/csetjmp "cpp/header/csetjmp")` | | | | --- | --- | --- | | ``` void longjmp( std::jmp_buf env, int status ); ``` | | (until C++17) | | ``` [[noreturn]] void longjmp( std::jmp_buf env, int status ); ``` | | (since C++17) | Loads the execution context `env` saved by a previous call to `[setjmp](setjmp "cpp/utility/program/setjmp")`. This function does not return. Control is transferred to the call site of the macro `[setjmp](setjmp "cpp/utility/program/setjmp")` that set up `env`. That `[setjmp](setjmp "cpp/utility/program/setjmp")` then returns the value, passed as the `status`. If the function that called `[setjmp](setjmp "cpp/utility/program/setjmp")` has exited, the behavior is undefined (in other words, only long jumps up the call stack are allowed). No destructors for automatic objects are called. If replacing of `std::longjmp` with `throw` and `[setjmp](setjmp "cpp/utility/program/setjmp")` with `catch` would execute a non-trivial destructor for any automatic object, the behavior of such `std::longjmp` is undefined. ### Parameters | | | | | --- | --- | --- | | env | - | variable referring to the execution state of the program saved by `[setjmp](http://en.cppreference.com/w/cpp/utility/program/setjmp)` | | status | - | the value to return from `[setjmp](setjmp "cpp/utility/program/setjmp")`. If it is equal to `​0​`, `1` is used instead | ### Return value (none). ### Notes `longjmp` is the mechanism used in C to handle unexpected error conditions where the function cannot return meaningfully. C++ generally uses [exception handling](../../language/exceptions "cpp/language/exceptions") for this purpose. ### Example ``` #include <iostream> #include <csetjmp> std::jmp_buf my_jump_buffer; [[noreturn]] void foo(int count) { std::cout << "foo(" << count << ") called\n"; std::longjmp(my_jump_buffer, count+1); // setjmp() will return count+1 } int main() { volatile int count = 0; // modified locals in setjmp scope must be volatile if (setjmp(my_jump_buffer) != 5) { // equality against constant expression in an if count = count + 1; // ++count, count += 1, etc on 'volatile'-qualified // left operand are deprecated since C++20 (P1152) foo(count); // This will cause setjmp() to exit } } ``` Output: ``` foo(1) called foo(2) called foo(3) called foo(4) called ``` ### See also | | | | --- | --- | | [setjmp](setjmp "cpp/utility/program/setjmp") | saves the context (function macro) | | [C documentation](https://en.cppreference.com/w/c/program/longjmp "c/program/longjmp") for `longjmp` | cpp std::at_quick_exit std::at\_quick\_exit ==================== | Defined in header `[<cstdlib>](../../header/cstdlib "cpp/header/cstdlib")` | | | | --- | --- | --- | | ``` int at_quick_exit( /*atexit-handler*/* func ) noexcept; int at_quick_exit( /*c-atexit-handler*/* func ) noexcept; ``` | (1) | (since C++11) | | ``` extern "C++" using /*atexit-handler*/ = void(); // exposition-only extern "C" using /*c-atexit-handler*/ = void(); // exposition-only ``` | (2) | | Registers the function pointed to by `func` to be called on quick program termination (via `[std::quick\_exit](quick_exit "cpp/utility/program/quick exit")`). Calling the function from several threads does not induce a data race. The implementation shall support the registration of at least `32` functions. The registered functions will not be called on [normal program termination](exit "cpp/utility/program/exit"). If a function need to be called in that case, `[std::atexit](atexit "cpp/utility/program/atexit")` must be used. ### Parameters | | | | | --- | --- | --- | | func | - | pointer to a function to be called on quick program termination | ### Return value `​0​` if the registration succeeds, nonzero value otherwise. ### Notes The two overloads are distinct because the types of the parameter `func` are distinct ([language linkage](../../language/language_linkage "cpp/language/language linkage") is part of its type). ### Example ### See also | | | | --- | --- | | [abort](abort "cpp/utility/program/abort") | causes abnormal program termination (without cleaning up) (function) | | [exit](exit "cpp/utility/program/exit") | causes normal program termination with cleaning up (function) | | [atexit](atexit "cpp/utility/program/atexit") | registers a function to be called on `[std::exit()](exit "cpp/utility/program/exit")` invocation (function) | | [quick\_exit](quick_exit "cpp/utility/program/quick exit") (C++11) | causes quick program termination without completely cleaning up (function) | | [C documentation](https://en.cppreference.com/w/c/program/at_quick_exit "c/program/at quick exit") for `at_quick_exit` | cpp EXIT_SUCCESS, EXIT_FAILURE EXIT\_SUCCESS, EXIT\_FAILURE ============================ | Defined in header `[<cstdlib>](../../header/cstdlib "cpp/header/cstdlib")` | | | | --- | --- | --- | | ``` #define EXIT_SUCCESS /*implementation defined*/ ``` | | | | ``` #define EXIT_FAILURE /*implementation defined*/ ``` | | | The `EXIT_SUCCESS` and `EXIT_FAILURE` macros expand into integral expressions that can be used as arguments to the `[std::exit](exit "cpp/utility/program/exit")` function (and, therefore, as the values to return from the [main function](../../language/main_function "cpp/language/main function")), and indicate program execution status. | Constant | Explanation | | --- | --- | | `EXIT_SUCCESS` | successful execution of a program | | `EXIT_FAILURE` | unsuccessful execution of a program | ### Notes Both `EXIT_SUCCESS` and the value zero indicate successful program execution status (see `[std::exit](exit "cpp/utility/program/exit")`), although it is not required that `EXIT_SUCCESS` equals zero. ### See also | | | --- | | [C documentation](https://en.cppreference.com/w/c/program/EXIT_status "c/program/EXIT status") for `EXIT_SUCCESS, EXIT_FAILURE` | cpp std::atexit std::atexit =========== | Defined in header `[<cstdlib>](../../header/cstdlib "cpp/header/cstdlib")` | | | | --- | --- | --- | | | (1) | | | ``` int atexit( /*c-atexit-handler*/* func ); int atexit( /*atexit-handler*/* func ); ``` | (until C++11) | | ``` int atexit( /*c-atexit-handler*/* func ) noexcept; int atexit( /*atexit-handler*/* func ) noexcept; ``` | (since C++11) | | ``` extern "C++" using /*atexit-handler*/ = void(); // exposition-only extern "C" using /*c-atexit-handler*/ = void(); // exposition-only ``` | (2) | | Registers the function pointed to by `func` to be called on normal program termination (via `[std::exit()](exit "cpp/utility/program/exit")` or returning from the [main function](../../language/main_function "cpp/language/main function")). | | | | --- | --- | | The functions will be called during the destruction of the static objects, in reverse order: if A was registered before B, then the call to B is made before the call to A. Same applies to the ordering between static object constructors and the calls to `atexit`: see `[std::exit](exit "cpp/utility/program/exit")`. | (until C++11) | | The functions may be called concurrently with the destruction of the objects with static storage duration and with each other, maintaining the guarantee that if registration of A was sequenced-before the registration of B, then the call to B is sequenced-before the call to A, same applies to the sequencing between static object constructors and calls to `atexit`: see `[std::exit](exit "cpp/utility/program/exit")`. | (since C++11) | The same function may be registered more than once. If a function exits via an exception, `[std::terminate](../../error/terminate "cpp/error/terminate")` is called. `atexit` is thread-safe: calling the function from several threads does not induce a data race. The implementation is guaranteed to support the registration of at least `32` functions. The exact limit is implementation-defined. ### Parameters | | | | | --- | --- | --- | | func | - | pointer to a function to be called on normal program termination | ### Return value `​0​` if the registration succeeds, nonzero value otherwise. ### Notes The two overloads are distinct because the types of the parameter `func` are distinct ([language linkage](../../language/language_linkage "cpp/language/language linkage") is part of its type). ### Example ``` #include <iostream> #include <cstdlib> void atexit_handler_1() { std::cout << "at exit #1\n"; } void atexit_handler_2() { std::cout << "at exit #2\n"; } int main() { const int result_1 = std::atexit(atexit_handler_1); const int result_2 = std::atexit(atexit_handler_2); if ((result_1 != 0) || (result_2 != 0)) { std::cerr << "Registration failed\n"; return EXIT_FAILURE; } std::cout << "returning from main\n"; return EXIT_SUCCESS; } ``` Output: ``` returning from main at exit #2 at exit #1 ``` ### See also | | | | --- | --- | | [abort](abort "cpp/utility/program/abort") | causes abnormal program termination (without cleaning up) (function) | | [exit](exit "cpp/utility/program/exit") | causes normal program termination with cleaning up (function) | | [quick\_exit](quick_exit "cpp/utility/program/quick exit") (C++11) | causes quick program termination without completely cleaning up (function) | | [at\_quick\_exit](at_quick_exit "cpp/utility/program/at quick exit") (C++11) | registers a function to be called on `[std::quick\_exit](quick_exit "cpp/utility/program/quick exit")` invocation (function) | | [C documentation](https://en.cppreference.com/w/c/program/atexit "c/program/atexit") for `atexit` | cpp std::sig_atomic_t std::sig\_atomic\_t =================== | Defined in header `[<csignal>](../../header/csignal "cpp/header/csignal")` | | | | --- | --- | --- | | ``` typedef /* unspecified */ sig_atomic_t; ``` | | | An integer type which can be accessed as an atomic entity even in the presence of asynchronous interrupts made by signals. ### Notes Until C++11, which introduced `[std::atomic](../../atomic/atomic "cpp/atomic/atomic")` and `[std::atomic\_signal\_fence](../../atomic/atomic_signal_fence "cpp/atomic/atomic signal fence")`, about the only thing a strictly conforming program could do in a signal handler was to assign a value to a `volatile static std::sig_atomic_t` variable and promptly return. ### See also | | | | --- | --- | | [signal](signal "cpp/utility/program/signal") | sets a signal handler for particular signal (function) | | [atomic\_signal\_fence](../../atomic/atomic_signal_fence "cpp/atomic/atomic signal fence") (C++11) | fence between a thread and a signal handler executed in the same thread (function) | | [C documentation](https://en.cppreference.com/w/c/program/sig_atomic_t "c/program/sig atomic t") for `sig_atomic_t` | cpp std::raise std::raise ========== | Defined in header `[<csignal>](../../header/csignal "cpp/header/csignal")` | | | | --- | --- | --- | | ``` int raise( int sig ); ``` | | | Sends signal sig to the program. The signal handler (specified using the `[std::signal()](signal "cpp/utility/program/signal")` function) is invoked. If the user-defined signal handling strategy is not set using `[std::signal()](signal "cpp/utility/program/signal")` yet, it is implementation-defined whether the signal will be ignored or default handler will be invoked. ### Parameters | | | | | | | --- | --- | --- | --- | --- | | sig | - | the signal to be sent. It can be an implementation-defined value or one of the following values: | | | | --- | --- | | [SIGABRTSIGFPESIGILLSIGINTSIGSEGVSIGTERM](sig_types "cpp/utility/program/SIG types") | defines signal types (macro constant) | | ### Return value `​0​` upon success, non-zero value on failure. ### Example ``` #include <csignal> #include <iostream> void signal_handler(int signal) { std::cout << "Received signal " << signal << '\n'; } int main() { // Install a signal handler std::signal(SIGTERM, signal_handler); std::cout << "Sending signal " << SIGTERM << '\n'; std::raise(SIGTERM); } ``` Possible output: ``` Sending signal 15 Received signal 15 ``` ### See also | | | | --- | --- | | [signal](signal "cpp/utility/program/signal") | sets a signal handler for particular signal (function) | | [C documentation](https://en.cppreference.com/w/c/program/raise "c/program/raise") for `raise` | cpp std::jmp_buf std::jmp\_buf ============= | Defined in header `[<csetjmp>](../../header/csetjmp "cpp/header/csetjmp")` | | | | --- | --- | --- | | ``` typedef /* unspecified */ jmp_buf; ``` | | | The `std::jmp_buf` type is an array type suitable for storing information to restore a calling environment. The stored information is sufficient to restore execution at the correct block of the program and invocation of that block. The state of floating-point status flags, or open files, or any other data is not stored in an object of type `jmp_buf`. ### Example ``` #include <iostream> #include <csetjmp> std::jmp_buf my_jump_buffer; [[noreturn]] void foo(int count) { std::cout << "foo(" << count << ") called\n"; std::longjmp(my_jump_buffer, count+1); // setjmp() will return count+1 } int main() { volatile int count = 0; // modified locals in setjmp scope must be volatile if (setjmp(my_jump_buffer) != 5) { // equality against constant expression in an if count = count + 1; // ++count, count += 1, etc on 'volatile'-qualified // left operand are deprecated since C++20 (P1152) foo(count); // This will cause setjmp() to exit } } ``` Output: ``` foo(1) called foo(2) called foo(3) called foo(4) called ``` ### See also | | | | --- | --- | | [setjmp](setjmp "cpp/utility/program/setjmp") | saves the context (function macro) | | [longjmp](longjmp "cpp/utility/program/longjmp") | jumps to specified location (function) | | [C documentation](https://en.cppreference.com/w/c/program/jmp_buf "c/program/jmp buf") for `jmp_buf` | cpp std::exit std::exit ========= | Defined in header `[<cstdlib>](../../header/cstdlib "cpp/header/cstdlib")` | | | | --- | --- | --- | | ``` void exit( int exit_code ); ``` | | (until C++11) | | ``` [[noreturn]] void exit( int exit_code ); ``` | | (since C++11) | Causes normal program termination to occur. Several cleanup steps are performed: | | | | --- | --- | | 1) Objects with static storage duration are destroyed and functions registered by calling `[std::atexit](atexit "cpp/utility/program/atexit")` are called: a) Non-local objects with static storage duration are destroyed in the reverse order of the completion of their constructor. b) Functions registered with `[std::atexit](atexit "cpp/utility/program/atexit")` are called in the reverse order of their registration, except that a function is called after any previously registered functions that had already been called at the time it was registered. c) For each function `f` registered with `[std::atexit](atexit "cpp/utility/program/atexit")` and each non-local object `obj` of static storage duration, * if `f` is registered before the initialization of `obj`, `f` will only be called after the destruction of `obj`; * if `f` is registered after the initialization of `obj`, `f` will only be called before the destruction of `obj`. d) For each local object `obj` with static storage duration, `obj` is destroyed as if a function calling the destructor of `obj` were registered with `[std::atexit](atexit "cpp/utility/program/atexit")` at the completion of the constructor of `obj`. | (until C++11) | | 1) The destructors of objects with thread local [storage duration](../../language/storage_duration "cpp/language/storage duration") that are associated with the current thread, the destructors of objects with static storage duration, and the functions registered with `[std::atexit](atexit "cpp/utility/program/atexit")` are executed concurrently, while maintaining the following guarantees: a) The last destructor for thread-local objects is [sequenced-before](../../language/eval_order "cpp/language/eval order") the first destructor for a static object b) If the completion of the constructor or [dynamic initialization](../../language/initialization#Dynamic_initialization "cpp/language/initialization") for thread-local or static object A was sequenced-before thread-local or static object B, the completion of the destruction of B is sequenced-before the start of the destruction of A c) If the completion of the initialization of a static object A was sequenced-before the call to `[std::atexit](atexit "cpp/utility/program/atexit")` for some function F, the call to F during termination is sequenced-before the start of the destruction of A d) If the call to `[std::atexit](atexit "cpp/utility/program/atexit")` for some function F was sequenced-before the completion of initialization of a static object A, the start of the destruction of A is sequenced-before the call to F during termination. e) If a call to `[std::atexit](atexit "cpp/utility/program/atexit")` for some function F1 was sequenced-before the call to `[std::atexit](atexit "cpp/utility/program/atexit")` for some function F2, then the call to F2 during termination is sequenced-before the call to F1 | (since C++11) | * In the above, + if any function registered with `atexit` or any destructor of static/thread-local object throws an exception, `[std::terminate](../../error/terminate "cpp/error/terminate")` is called + if the compiler opted to lift dynamic initialization of an object to the static initialization phase of [non-local initialization](../../language/initialization "cpp/language/initialization"), the sequencing of destruction honors its would-be dynamic initialization. + If a function-local (block-scope) static object was destroyed and then that function is called from the destructor of another static object and the control flow passes through the definition of that object (or if it is used indirectly, via pointer or reference), the behavior is undefined. + if a function-local (block-scope) static object was initialized during construction of a subobject of a class or array, it is only destroyed after all subobjects of that class or all elements of that array were destroyed. 2) all C streams are flushed and closed 3) files created by `[std::tmpfile](../../io/c/tmpfile "cpp/io/c/tmpfile")` are removed 4) control is returned to the host environment. If `exit_code` is `0` or `[EXIT\_SUCCESS](exit_status "cpp/utility/program/EXIT status")`, an implementation-defined status indicating successful termination is returned. If `exit_code` is `[EXIT\_FAILURE](exit_status "cpp/utility/program/EXIT status")`, an implementation-defined status indicating unsuccessful termination is returned. In other cases implementation-defined status value is returned. Stack is not unwound: destructors of variables with automatic [storage duration](../../language/storage_duration "cpp/language/storage duration") are not called. ### Relationship with the main function Returning from the [main function](../../language/main_function "cpp/language/main function"), either by a `return` statement or by reaching the end of the function performs the normal function termination (calls the destructors of the variables with automatic [storage durations](../../language/storage_duration "cpp/language/storage duration")) and then executes `std::exit`, passing the argument of the return statement (or `​0​` if implicit return was used) as `exit_code`. ### Parameters | | | | | --- | --- | --- | | exit\_code | - | exit status of the program | ### Return value (none). ### Example ``` #include <iostream> #include <cstdlib> struct Static { ~Static() { std::cout << "Static destructor\n"; } }; struct Local { ~Local() { std::cout << "Local destructor\n"; } }; Static static_variable; // destructor of this object *will* be called void atexit_handler() { std::cout << "atexit handler\n"; } int main() { Local local_variable; // destructor of this object will *not* be called const int result = std::atexit(atexit_handler); // handler will be called if (result != 0) { std::cerr << "atexit registration failed\n"; return EXIT_FAILURE; } std::cout << "test\n"; std::exit(EXIT_FAILURE); std::cout << "this line will *not* be executed\n"; } ``` Output: ``` test atexit handler Static destructor ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 3](https://cplusplus.github.io/LWG/issue3) | C++98 | during cleanup, the behavior was unclear when (1) a function isregistered with `[std::atexit](atexit "cpp/utility/program/atexit")` or (2) a static local object is initialized | made clear | ### See also | | | | --- | --- | | [abort](abort "cpp/utility/program/abort") | causes abnormal program termination (without cleaning up) (function) | | [atexit](atexit "cpp/utility/program/atexit") | registers a function to be called on `std::exit()` invocation (function) | | [quick\_exit](quick_exit "cpp/utility/program/quick exit") (C++11) | causes quick program termination without completely cleaning up (function) | | [at\_quick\_exit](at_quick_exit "cpp/utility/program/at quick exit") (C++11) | registers a function to be called on `[std::quick\_exit](quick_exit "cpp/utility/program/quick exit")` invocation (function) | | [C documentation](https://en.cppreference.com/w/c/program/exit "c/program/exit") for `exit` |
programming_docs
cpp std::getenv std::getenv =========== | Defined in header `[<cstdlib>](../../header/cstdlib "cpp/header/cstdlib")` | | | | --- | --- | --- | | ``` char* getenv( const char* env_var ); ``` | | | Searches the *environment list* provided by the host environment (the OS), for a string that matches the C string pointed to by `env_var` and returns a pointer to the C string that is associated with the matched environment list member. | | | | --- | --- | | This function is not required to be thread-safe. Another call to getenv, as well as a call to the POSIX functions [setenv()](http://pubs.opengroup.org/onlinepubs/9699919799/functions/setenv.html), [unsetenv()](http://pubs.opengroup.org/onlinepubs/9699919799/functions/unsetenv.html), and [putenv()](http://pubs.opengroup.org/onlinepubs/9699919799/functions/putenv.html) may invalidate the pointer returned by a previous call or modify the string obtained from a previous call. | (until C++11) | | This function is thread-safe (calling it from multiple threads does not introduce a data race) as long as no other function modifies the host environment. In particular, the POSIX functions [setenv()](http://pubs.opengroup.org/onlinepubs/9699919799/functions/setenv.html), [unsetenv()](http://pubs.opengroup.org/onlinepubs/9699919799/functions/unsetenv.html), and [putenv()](http://pubs.opengroup.org/onlinepubs/9699919799/functions/putenv.html) would introduce a data race if called without synchronization. | (since C++11) | Modifying the string returned by `getenv` invokes undefined behavior. ### Parameters | | | | | --- | --- | --- | | env\_var | - | null-terminated character string identifying the name of the environmental variable to look for | ### Return value Character string identifying the value of the environmental variable or null pointer if such variable is not found. ### Notes On POSIX systems, the [environment variables](http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap08.html#tag_08) are also accessible through the global variable `environ`, declared as `extern char **environ;` in `<unistd.h>`, and through the optional third argument, `envp`, of [the main function](../../language/main_function "cpp/language/main function"). ### Example ``` #include <iostream> #include <cstdlib> int main() { if(const char* env_p = std::getenv("PATH")) std::cout << "Your PATH is: " << env_p << '\n'; } ``` Possible output: ``` Your PATH is: /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games ``` ### See also | | | --- | | [C documentation](https://en.cppreference.com/w/c/program/getenv "c/program/getenv") for `getenv` | cpp std::signal std::signal =========== | Defined in header `[<csignal>](../../header/csignal "cpp/header/csignal")` | | | | --- | --- | --- | | ``` /*signal-handler*/* signal(int sig, /*signal-handler*/* handler); ``` | (1) | | | ``` extern "C" using /*signal-handler*/ = void(int); // exposition-only ``` | (2) | | Sets the handler for signal `sig`. The signal handler can be set so that default handling will occur, signal is ignored, or a user-defined function is called. When signal handler is set to a function and a signal occurs, it is implementation defined whether `std::signal(sig, [SIG\_DFL](http://en.cppreference.com/w/cpp/utility/program/SIG_strategies))` will be executed immediately before the start of signal handler. Also, the implementation can prevent some implementation-defined set of signals from occurring while the signal handler runs. For some of the signals, the implementation may call `std::signal(sig, [SIG\_IGN](http://en.cppreference.com/w/cpp/utility/program/SIG_strategies))` at the startup of the program. For the rest, the implementation must call `std::signal(sig, [SIG\_DFL](http://en.cppreference.com/w/cpp/utility/program/SIG_strategies))`. (Note: POSIX introduced [`sigaction`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/sigaction.html) to standardize these implementation-defined behaviors). ### Parameters | | | | | | | --- | --- | --- | --- | --- | | sig | - | the signal to set the signal handler to. It can be an implementation-defined value or one of the following values: | | | | --- | --- | | [SIGABRTSIGFPESIGILLSIGINTSIGSEGVSIGTERM](sig_types "cpp/utility/program/SIG types") | defines signal types (macro constant) | | | handler | - | the signal handler. This must be one of the following: * `[SIG\_DFL](sig_strategies "cpp/utility/program/SIG strategies")` macro. The signal handler is set to default signal handler. * `[SIG\_IGN](sig_strategies "cpp/utility/program/SIG strategies")` macro. The signal is ignored. * pointer to a function. The signature of the function must be equivalent to the following: | | | | | --- | --- | --- | | ``` extern "C" void fun(int sig); ``` | | | | ### Return value Previous signal handler on success or `[SIG\_ERR](sig_err "cpp/utility/program/SIG ERR")` on failure (setting a signal handler can be disabled on some implementations). ### Signal handler The following limitations are imposed on the user-defined function that is installed as a signal handler. | | | | --- | --- | | If the signal handler is called NOT as a result of `[std::abort](abort "cpp/utility/program/abort")` or `[std::raise](raise "cpp/utility/program/raise")` (asynchronous signal), the behavior is undefined if.* the signal handler calls any function within the standard library, except + `[std::abort](abort "cpp/utility/program/abort")` + `[std::\_Exit](_exit "cpp/utility/program/ Exit")` + `[std::quick\_exit](quick_exit "cpp/utility/program/quick exit")` + `std::signal` with the first argument being the number of the signal currently handled (async handler can re-register itself, but not other signals). * the signal handler refers to any object with static storage duration that is not `[std::atomic](../../atomic/atomic "cpp/atomic/atomic")`(since C++11) or `volatile [std::sig\_atomic\_t](http://en.cppreference.com/w/cpp/utility/program/sig_atomic_t)`. | (until C++17) | | The behavior is undefined if any signal handler performs any of the following:* call to any library function, except the following *signal-safe* functions (note, in particular, dynamic allocation is not signal-safe): + members functions of `[std::atomic](../../atomic/atomic "cpp/atomic/atomic")` and non-member functions from [`<atomic>`](../../header/atomic "cpp/header/atomic") if the atomic type they operate on is lock-free. The functions `[std::atomic\_is\_lock\_free](../../atomic/atomic_is_lock_free "cpp/atomic/atomic is lock free")` and `[std::atomic::is\_lock\_free](../../atomic/atomic/is_lock_free "cpp/atomic/atomic/is lock free")` are signal-safe for any atomic type. + `std::signal` with the first argument being the number of the signal currently handled (signal handler can re-register itself, but not other signals). + member functions of `[std::numeric\_limits](../../types/numeric_limits "cpp/types/numeric limits")` + `[std::\_Exit](_exit "cpp/utility/program/ Exit")` + `[std::abort](abort "cpp/utility/program/abort")` + `[std::quick\_exit](quick_exit "cpp/utility/program/quick exit")` + The member functions of `[std::initializer\_list](../initializer_list "cpp/utility/initializer list")` and the `std::initializer_list` overloads of `[std::begin](../../iterator/begin "cpp/iterator/begin")` and `[std::end](../../iterator/end "cpp/iterator/end")` + `[std::forward](../forward "cpp/utility/forward")`, `std::move`, `[std::move\_if\_noexcept](../move_if_noexcept "cpp/utility/move if noexcept")` + All functions from [`<type_traits>`](../../header/type_traits "cpp/header/type traits") + `[std::memcpy](../../string/byte/memcpy "cpp/string/byte/memcpy")` and `[std::memmove](../../string/byte/memmove "cpp/string/byte/memmove")` * access to an object with thread storage duration * a [`dynamic_cast`](../../language/dynamic_cast "cpp/language/dynamic cast") expression * a [`throw`](../../language/throw "cpp/language/throw") expression * entry to a [`try`](../../language/try_catch "cpp/language/try catch") block, including [function-`try`-block](../../language/function-try-block "cpp/language/function-try-block") * initialization of a static variable that performs [dynamic non-local initialization](../../language/initialization#Non-local_variables "cpp/language/initialization") (including delayed until first ODR-use) * waits for completion of initialization of any variable with static storage duration due to another thread concurrently initializing it | (since C++17) | If the user defined function returns when handling `[SIGFPE](sig_types "cpp/utility/program/SIG types")`, `[SIGILL](sig_types "cpp/utility/program/SIG types")`, `[SIGSEGV](sig_types "cpp/utility/program/SIG types")` or any other implementation-defined signal specifying a computational exception, the behavior is undefined. If the signal handler is called as a result of `[std::abort](abort "cpp/utility/program/abort")` or `[std::raise](raise "cpp/utility/program/raise")` (synchronous signal), the behavior is undefined if the signal handler calls `[std::raise](raise "cpp/utility/program/raise")`. | | | | --- | --- | | On entry to the signal handler, the state of the [floating-point environment](../../numeric/fenv "cpp/numeric/fenv") and the values of all objects is unspecified, except for.* objects of type `volatile [std::sig\_atomic\_t](http://en.cppreference.com/w/cpp/utility/program/sig_atomic_t)` * objects of lock-free `[std::atomic](../../atomic/atomic "cpp/atomic/atomic")` types (since C++11) * side effects made visible through `[std::atomic\_signal\_fence](../../atomic/atomic_signal_fence "cpp/atomic/atomic signal fence")` (since C++11) On return from a signal handler, the value of any object modified by the signal handler that is not `volatile [std::sig\_atomic\_t](http://en.cppreference.com/w/cpp/utility/program/sig_atomic_t)` or lock-free `[std::atomic](../../atomic/atomic "cpp/atomic/atomic")` is indeterminate. | (until C++14) | | A call to the function `signal()` [synchronizes-with](../../atomic/memory_order "cpp/atomic/memory order") any resulting invocation of the signal handler. If a signal handler is executed as a result of a call to `[std::raise](raise "cpp/utility/program/raise")` (synchronously), then the execution of the handler is *sequenced-after* the invocation of `std::raise` and *sequenced-before* the return from it and runs on the same thread as `std::raise`. Execution of the handlers for other signals is *unsequenced* with respect to the rest of the program and runs on an unspecified thread. Two accesses to the same object of type `volatile [std::sig\_atomic\_t](http://en.cppreference.com/w/cpp/utility/program/sig_atomic_t)` do not result in a data race if both occur in the same thread, even if one or more occurs in a signal handler. For each signal handler invocation, evaluations performed by the thread invoking a signal handler can be divided into two groups A and B, such that no evaluations in B *happen-before* evaluations in A, and the evaluations of such `volatile [std::sig\_atomic\_t](http://en.cppreference.com/w/cpp/utility/program/sig_atomic_t)` objects take values as though all evaluations in A [happened-before](../../atomic/memory_order "cpp/atomic/memory order") the execution of the signal handler and the execution of the signal handler *happened-before* all evaluations in B. | (since C++14) | ### Notes POSIX requires that `signal` is thread-safe, and [specifies a list of async-signal-safe library functions](http://pubs.opengroup.org/onlinepubs/9699919799/functions/V2_chap02.html#tag_15_04) that may be called from any signal handler. | | | | --- | --- | | Signal handlers are expected to have [C linkage](../../language/language_linkage "cpp/language/language linkage") and, in general, only use the features from the common subset of C and C++. It is implementation-defined if a function with C++ linkage can be used as a signal handler. | (until C++17) | | There is no restriction on the linkage of signal handlers. | (since C++17) | ### Example ``` #include <csignal> #include <iostream> namespace { volatile std::sig_atomic_t gSignalStatus; } void signal_handler(int signal) { gSignalStatus = signal; } int main() { // Install a signal handler std::signal(SIGINT, signal_handler); std::cout << "SignalValue: " << gSignalStatus << '\n'; std::cout << "Sending signal: " << SIGINT << '\n'; std::raise(SIGINT); std::cout << "SignalValue: " << gSignalStatus << '\n'; } ``` Possible output: ``` SignalValue: 0 Sending signal: 2 SignalValue: 2 ``` ### References * C++20 standard (ISO/IEC 14882:2020): + 17.13.5 Signal handlers [support.signal] * C++17 standard (ISO/IEC 14882:2017): + 21.10.4 Signal handlers [support.signal] ### See also | | | | --- | --- | | [raise](raise "cpp/utility/program/raise") | runs the signal handler for particular signal (function) | | [atomic\_signal\_fence](../../atomic/atomic_signal_fence "cpp/atomic/atomic signal fence") (C++11) | fence between a thread and a signal handler executed in the same thread (function) | | [C documentation](https://en.cppreference.com/w/c/program/signal "c/program/signal") for `signal` | cpp std::basic_format_string, std::format_string, std::wformat_string std::basic\_format\_string, std::format\_string, std::wformat\_string ===================================================================== | Defined in header `[<format>](../../header/format "cpp/header/format")` | | | | --- | --- | --- | | ``` template< class CharT, class... Args > struct basic_format_string; ``` | (1) | (since C++20) | | ``` template< class... Args > using format_string = basic_format_string<char, std::type_identity_t<Args>...>; ``` | (2) | (since C++20) | | ``` template< class... Args > using wformat_string = basic_format_string<wchar_t, std::type_identity_t<Args>...>; ``` | (3) | (since C++20) | Class template `std::basic_format_string` wraps a `[std::basic\_string\_view](../../string/basic_string_view "cpp/string/basic string view")` and performs compile-time format string checks at construction time. ### Member functions | | | | --- | --- | | (constructor) | constructs a `basic_format_string`, raising compile error if the argument is not a format string (public member function) | | get | returns the wrapped string (public member function) | std::basic\_format\_string::basic\_format\_string -------------------------------------------------- | | | | | --- | --- | --- | | ``` template< class T > consteval basic_format_string( const T& s ); ``` | | | Constructs a `basic_format_string` object that stores a view of string `s`. If the argument is not a compile-time constant, or if it cannot be parsed as a format string for the formatting argument types `Args`, the construction is ill-formed. This overload participates in overload resolution only if `const T&` models `[std::convertible\_to](http://en.cppreference.com/w/cpp/concepts/convertible_to)<[std::basic\_string\_view](http://en.cppreference.com/w/cpp/string/basic_string_view)<CharT>>`. ### Parameters | | | | | | | | | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | s | - | an object that represents the format string. The format string consists of * ordinary characters (except `{` and `}`), which are copied unchanged to the output, * escape sequences `{{` and `}}`, which are replaced with `{` and `}` respectively in the output, and * replacement fields. Each replacement field has the following format: | | | | | --- | --- | --- | | `{` arg-id (optional) `}` | (1) | | | `{` arg-id (optional) `:` format-spec `}` | (2) | | 1) replacement field without a format specification 2) replacement field with a format specification | | | | | --- | --- | --- | | arg-id | - | specifies the index of the argument in `args` whose value is to be used for formatting; if it is omitted, the arguments are used in order. The arg-ids in a format string must all be present or all be omitted. Mixing manual and automatic indexing is an error. | | format-spec | - | the format specification defined by the `[std::formatter](formatter "cpp/utility/format/formatter")` specialization for the corresponding argument. | * For basic types and standard string types, the format specification is interpreted as [standard format specification](formatter#Standard_format_specification "cpp/utility/format/formatter"). * For chrono types, the format specification is interpreted as [chrono format specification](../../chrono/system_clock/formatter#Format_specification "cpp/chrono/system clock/formatter"). * For other formattable types, the format specification is determined by user-defined `formatter` specializations. | std::basic\_format\_string::get -------------------------------- | | | | | --- | --- | --- | | ``` constexpr std::basic_string_view<CharT> get() const noexcept; ``` | | | Returns the stored string view. ### Notes The alias templates `format_string` and `wformat_string` use `std::type_identity_t` to inhibit template argument deduction. Typically, when they appear as a function parameter, their template arguments are deduced from other function arguments. ``` template< class... Args > std::string format( std::format_string<Args...> fmt, Args&&... args ); auto s = format("{} {}", 1.0, 2); // Calls format<double, int>. Args are deduced from 1.0, 2 // Due to the use of type_identity_t in format_string, template argument deduction // does not consider the type of the format string. ``` ### Example ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [P2508R1](https://wg21.link/P2508R1) | C++20 | there's no user-visible name for this facility | the name `basic_format_string` is exposed | cpp std::format std::format =========== | Defined in header `[<format>](../../header/format "cpp/header/format")` | | | | --- | --- | --- | | ``` template< class... Args > std::string format( std::format_string<Args...> fmt, Args&&... args ); ``` | (1) | (since C++20) | | ``` template< class... Args > std::wstring format( std::wformat_string<Args...> fmt, Args&&... args ); ``` | (2) | (since C++20) | | ``` template< class... Args > std::string format( const std::locale& loc, std::format_string<Args...> fmt, Args&&... args ); ``` | (3) | (since C++20) | | ``` template< class... Args > std::wstring format( const std::locale& loc, std::wformat_string<Args...> fmt, Args&&... args ); ``` | (4) | (since C++20) | Format `args` according to the format string `fmt`, and return the result as a string. If present, `loc` is used for locale-specific formatting. 1) equivalent to `return [std::vformat](http://en.cppreference.com/w/cpp/utility/format/vformat)(fmt.get(), [std::make\_format\_args](http://en.cppreference.com/w/cpp/utility/format/make_format_args)(args...));` 2) equivalent to `return [std::vformat](http://en.cppreference.com/w/cpp/utility/format/vformat)(fmt.get(), [std::make\_wformat\_args](http://en.cppreference.com/w/cpp/utility/format/make_format_args)(args...));` 3) equivalent to `return [std::vformat](http://en.cppreference.com/w/cpp/utility/format/vformat)(loc, fmt.get(), [std::make\_format\_args](http://en.cppreference.com/w/cpp/utility/format/make_format_args)(args...));` 4) equivalent to `return [std::vformat](http://en.cppreference.com/w/cpp/utility/format/vformat)(loc, fmt.get(), [std::make\_wformat\_args](http://en.cppreference.com/w/cpp/utility/format/make_format_args)(args...));` The behavior is undefined if `[std::formatter](http://en.cppreference.com/w/cpp/utility/format/formatter)<Ti, CharT>` does not meet the [BasicFormatter](../../named_req/basicformatter "cpp/named req/BasicFormatter") requirements for any `Ti` in `Args` (as required by `[std::make\_format\_args](http://en.cppreference.com/w/cpp/utility/format/make_format_args)` and `[std::make\_wformat\_args](http://en.cppreference.com/w/cpp/utility/format/make_format_args)`), where `CharT` is `char` for overloads (1,3), `wchar_t` for overloads (2,4). ### Parameters | | | | | | | | | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | fmt | - | an object that represents the format string. The format string consists of * ordinary characters (except `{` and `}`), which are copied unchanged to the output, * escape sequences `{{` and `}}`, which are replaced with `{` and `}` respectively in the output, and * replacement fields. Each replacement field has the following format: | | | | | --- | --- | --- | | `{` arg-id (optional) `}` | (1) | | | `{` arg-id (optional) `:` format-spec `}` | (2) | | 1) replacement field without a format specification 2) replacement field with a format specification | | | | | --- | --- | --- | | arg-id | - | specifies the index of the argument in `args` whose value is to be used for formatting; if it is omitted, the arguments are used in order. The arg-ids in a format string must all be present or all be omitted. Mixing manual and automatic indexing is an error. | | format-spec | - | the format specification defined by the `[std::formatter](formatter "cpp/utility/format/formatter")` specialization for the corresponding argument. | * For basic types and standard string types, the format specification is interpreted as [standard format specification](formatter#Standard_format_specification "cpp/utility/format/formatter"). * For chrono types, the format specification is interpreted as [chrono format specification](../../chrono/system_clock/formatter#Format_specification "cpp/chrono/system clock/formatter"). * For other formattable types, the format specification is determined by user-defined `formatter` specializations. | | args... | - | arguments to be formatted | | loc | - | `[std::locale](../../locale/locale "cpp/locale/locale")` used for locale-specific formatting | ### Return value A string object holding the formatted result. ### Exceptions Throws `[std::bad\_alloc](../../memory/new/bad_alloc "cpp/memory/new/bad alloc")` on allocation failure. Also propagates exception thrown by any formatter. ### Notes It is not an error to provide more arguments than the format string requires: ``` std::format("{} {}!", "Hello", "world", "something"); // OK, produces "Hello world!" ``` As of [P2216R3](https://wg21.link/P2216R3), it is an error if the format string is not a constant expression. `[std::vformat](vformat "cpp/utility/format/vformat")` can be used in this case. ``` std::string f(std::string_view runtime_format_string) { // return std::format(runtime_format_string, "foo", "bar"); // error return std::vformat(runtime_format_string, std::make_format_args("foo", "bar")); // ok } ``` ### Example ``` #include <format> #include <iostream> #include <string> #include <string_view> template <typename... Args> std::string dyna_print(std::string_view rt_fmt_str, Args&&... args) { return std::vformat(rt_fmt_str, std::make_format_args(args...)); } int main() { std::cout << std::format("Hello {}!\n", "world"); std::string fmt; for (int i{}; i != 3; ++i) { fmt += "{} "; // constructs the formatting string std::cout << fmt << " : "; std::cout << dyna_print(fmt, "alpha", 'Z', 3.14, "unused"); std::cout << '\n'; } } ``` Output: ``` Hello world! {} : alpha {} {} : alpha Z {} {} {} : alpha Z 3.14 ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [P2216R3](https://wg21.link/P2216R3) | C++20 | throws `[std::format\_error](format_error "cpp/utility/format/format error")` for invalid format string | invalid format string results in compile-time error | | [P2418R2](https://wg21.link/P2418R2) | C++20 | objects that are neither const-usable nor copyable(such as generator-like objects) are not formattable | allow formatting these objects | | [P2508R1](https://wg21.link/P2508R1) | C++20 | there's no user-visible name for this facility | the name `basic_format_string` is exposed | ### See also | | | | --- | --- | | [format\_to](format_to "cpp/utility/format/format to") (C++20) | writes out formatted representation of its arguments through an output iterator (function template) | | [format\_to\_n](format_to_n "cpp/utility/format/format to n") (C++20) | writes out formatted representation of its arguments through an output iterator, not exceeding specified size (function template) |
programming_docs
cpp std::format_to_n, std::format_to_n_result std::format\_to\_n, std::format\_to\_n\_result ============================================== | Defined in header `[<format>](../../header/format "cpp/header/format")` | | | | --- | --- | --- | | ``` template< class OutputIt, class... Args > std::format_to_n_result<OutputIt> format_to_n( OutputIt out, std::iter_difference_t<OutputIt> n, std::format_string<Args...> fmt, Args&&... args ); ``` | (1) | (since C++20) | | ``` template< class OutputIt, class... Args > std::format_to_n_result<OutputIt> format_to_n( OutputIt out, std::iter_difference_t<OutputIt> n, std::wformat_string<Args...> fmt, Args&&... args ); ``` | (2) | (since C++20) | | ``` template< class OutputIt, class... Args > std::format_to_n_result<OutputIt> format_to_n( OutputIt out, std::iter_difference_t<OutputIt> n, const std::locale& loc, std::format_string<Args...> fmt, Args&&... args ); ``` | (3) | (since C++20) | | ``` template< class OutputIt, class... Args > std::format_to_n_result<OutputIt> format_to_n( OutputIt out, std::iter_difference_t<OutputIt> n, const std::locale& loc, std::wformat_string<Args...> fmt, Args&&... args ); ``` | (4) | (since C++20) | | ``` template< class OutputIt > struct format_to_n_result { OutputIt out; std::iter_difference_t<OutputIt> size; }; ``` | (5) | (since C++20) | Format `args` according to the format string `fmt`, and write the result to the output iterator `out`. At most `n` characters are written. If present, `loc` is used for locale-specific formatting. Let `CharT` be `char` for overloads (1,3), `wchar_t` for overloads (2,4). These overloads participate in overload resolution only if `OutputIt` satisfies the concept `[std::output\_iterator](http://en.cppreference.com/w/cpp/iterator/output_iterator)<const CharT&>`. The behavior is undefined if `OutputIt` does not model (meet the semantic requirements of) the concept `[std::output\_iterator](http://en.cppreference.com/w/cpp/iterator/output_iterator)<const CharT&>`, or if `[std::formatter](http://en.cppreference.com/w/cpp/utility/format/formatter)<[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<Ti>, CharT>` does not meet the [BasicFormatter](../../named_req/basicformatter "cpp/named req/BasicFormatter") requirements for any `Ti` in `Args`. 5) `std::format_to_n_result` has no base classes, or members other than `out`, `size` and implicitly declared special member functions. ### Parameters | | | | | --- | --- | --- | | out | - | iterator to the output buffer | | n | - | maximum number of characters to be written to the buffer | | fmt | - | an object that represents the format string. The format string consists of * ordinary characters (except `{` and `}`), which are copied unchanged to the output, * escape sequences `{{` and `}}`, which are replaced with `{` and `}` respectively in the output, and * replacement fields. Each replacement field has the following format: | | | | | --- | --- | --- | | `{` arg-id (optional) `}` | (1) | | | `{` arg-id (optional) `:` format-spec `}` | (2) | | 1) replacement field without a format specification 2) replacement field with a format specification | | | | | --- | --- | --- | | arg-id | - | specifies the index of the argument in `args` whose value is to be used for formatting; if it is omitted, the arguments are used in order. The arg-ids in a format string must all be present or all be omitted. Mixing manual and automatic indexing is an error. | | format-spec | - | the format specification defined by the `[std::formatter](formatter "cpp/utility/format/formatter")` specialization for the corresponding argument. | * For basic types and standard string types, the format specification is interpreted as [standard format specification](formatter#Standard_format_specification "cpp/utility/format/formatter"). * For chrono types, the format specification is interpreted as [chrono format specification](../../chrono/system_clock/formatter#Format_specification "cpp/chrono/system clock/formatter"). * For other formattable types, the format specification is determined by user-defined `formatter` specializations. | | args... | - | arguments to be formatted | | loc | - | `[std::locale](../../locale/locale "cpp/locale/locale")` used for locale-specific formatting | ### Return value A `format_to_n_result` such that the `out` member is an iterator past the end of the output range, and the `size` member is the total (not truncated) output size. ### Exceptions Propagates any exception thrown by formatter or iterator operations. ### Example ``` #include <format> #include <iostream> #include <string_view> int main() { char buffer[64]; const auto result = std::format_to_n(buffer, std::size(buffer) - 1, "Hubble's H{2} {3} {0}{4}{1} km/sec/Mpc.", 71, // {0}, occupies 2 bytes 8, // {1}, occupies 1 byte "\u2080", // {2}, occupies 3 bytes "\u2245", // {3}, occupies 3 bytes "\u00B1" // {4}, occupies 2 bytes ); *result.out = '\0'; const std::string_view str{buffer, result.out}; // uses C++20 ctor std::cout << "Buffer: \"" << str << "\"\n" << "Buffer size = " << std::size(buffer) << '\n' << "Untruncated output size = " << result.size << '\n'; } ``` Output: ``` Buffer: "Hubble's H₀ ≅ 71±8 km/sec/Mpc." Buffer size = 64 Untruncated output size = 35 ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [P2216R3](https://wg21.link/P2216R3) | C++20 | throws `[std::format\_error](format_error "cpp/utility/format/format error")` for invalid format string | invalid format string results in compile-time error | | [P2418R2](https://wg21.link/P2418R2) | C++20 | objects that are neither const-usable nor copyable(such as generator-like objects) are not formattable | allow formatting these objects | | [P2508R1](https://wg21.link/P2508R1) | C++20 | there's no user-visible name for this facility | the name `basic_format_string` is exposed | ### See also | | | | --- | --- | | [format](format "cpp/utility/format/format") (C++20) | stores formatted representation of the arguments in a new string (function template) | | [format\_to](format_to "cpp/utility/format/format to") (C++20) | writes out formatted representation of its arguments through an output iterator (function template) | | [formatted\_size](formatted_size "cpp/utility/format/formatted size") (C++20) | determines the number of characters necessary to store the formatted representation of its arguments (function template) | cpp std::basic_format_arg std::basic\_format\_arg ======================= | Defined in header `[<format>](../../header/format "cpp/header/format")` | | | | --- | --- | --- | | ``` template< class Context > class basic_format_arg; ``` | | (since C++20) | Provides access to a formatting argument. `basic_format_arg` objects are typically created by `[std::make\_format\_args](make_format_args "cpp/utility/format/make format args")` and accessed through `[std::visit\_format\_arg](visit_format_arg "cpp/utility/format/visit format arg")`. A `basic_format_arg` object behaves as if it stores a `[std::variant](../variant "cpp/utility/variant")` of the following types: * `[std::monostate](http://en.cppreference.com/w/cpp/utility/variant/monostate)` (only if the object was default-constructed) * `bool` * `Context::char_type` * `int` * `unsigned int` * `long long int` * `unsigned long long int` * `float` * `double` * `long double` * `const Context::char_type*` * `[std::basic\_string\_view](http://en.cppreference.com/w/cpp/string/basic_string_view)<Context::char\_type>` * `const void*` * `basic_format_arg::handle` ### Member classes | Type | Definition | | --- | --- | | handle | type-erased wrapper that allows formatting an object of user-defined type (class) | ### Member functions | | | | --- | --- | | (constructor) | constructs a `std::basic_format_arg` (public member function) | | operator bool | checks if the current object holds a formatting argument (public member function) | ### Non-member functions | | | | --- | --- | | [visit\_format\_arg](visit_format_arg "cpp/utility/format/visit format arg") (C++20) | argument visitation interface for user-defined formatters (function template) | std::basic\_format\_arg::handle -------------------------------- | | | | | --- | --- | --- | | ``` template< class Context > class basic_format_arg<Context>::handle; ``` | | | Allows formatting an object of a user-defined type. ### Member functions | | | | --- | --- | | format | formats the referenced object with the given contexts (public member function) | std::basic\_format\_arg::handle::format ---------------------------------------- | | | | | --- | --- | --- | | ``` void format( std::basic_format_parse_context<Context::char_type>& parse_ctx, Context& format_ctx ) const; ``` | | | Let `T` be the type of the associated formatting argument, `ref` be a `const T&` that refers to the formatting argument. Equivalent to: `typename Context::template formatter_type<T> f; parse_ctx.advance_to(f.parse(parse_ctx)); format_ctx.advance_to(f.format(ref, format_ctx));` std::basic\_format\_arg::basic\_format\_arg -------------------------------------------- | | | | | --- | --- | --- | | ``` basic_format_arg() noexcept; ``` | | | Default constructor. Constructs a `basic_format_arg` that does not hold a formatting argument. The stored object has type `[std::monostate](../variant/monostate "cpp/utility/variant/monostate")`. To create a `basic_format_arg` that holds a formatting argument, `[std::make\_format\_args](make_format_args "cpp/utility/format/make format args")` has to be used. std::basic\_format\_arg::operator bool --------------------------------------- | | | | | --- | --- | --- | | ``` explicit operator bool() const noexcept; ``` | | | Checks whether `*this` holds a formatting argument. Returns `true` if `*this` holds a formatting argument (i.e. the stored object does not have type `[std::monostate](../variant/monostate "cpp/utility/variant/monostate")`), `false` otherwise. ### Example ### See also | | | | --- | --- | | [basic\_format\_argsformat\_argswformat\_args](basic_format_args "cpp/utility/format/basic format args") (C++20)(C++20)(C++20) | class that provides access to all formatting arguments (class template) | cpp std::basic_format_context std::basic\_format\_context =========================== | Defined in header `[<format>](../../header/format "cpp/header/format")` | | | | --- | --- | --- | | ``` template< class OutputIt, class CharT > class basic_format_context; ``` | (1) | (since C++20) | | ``` using format_context = basic_format_context</* unspecified */, char>; ``` | (2) | (since C++20) | | ``` using wformat_context = basic_format_context</* unspecified */, wchar_t>; ``` | (3) | (since C++20) | Provides access to formatting state consisting of the formatting arguments and the output iterator. The behavior is undefined if `OutputIt` does not model `std::output_iterator<const CharT&>`. 2) The unspecified template argument is an output iterator that appends to `[std::string](../../string/basic_string "cpp/string/basic string")`, such as `[std::back\_insert\_iterator](http://en.cppreference.com/w/cpp/iterator/back_insert_iterator)<[std::string](http://en.cppreference.com/w/cpp/string/basic_string)>`. Implementations are encouraged to use an iterator to type-erased buffer type that supports appending to any contiguous and resizable container. 3) The unspecified template argument is an output iterator that appends to `[std::wstring](../../string/basic_string "cpp/string/basic string")`. ### Member types | Type | Definition | | --- | --- | | `iterator` | `OutputIt` | | `char_type` | `CharT` | ### Member alias templates | Type | Definition | | --- | --- | | `formatter_type<T>` | `[std::formatter](http://en.cppreference.com/w/cpp/utility/format/formatter)<T, CharT>` | ### Member functions | | | | --- | --- | | arg | returns the argument at the given index (public member function) | | locale | returns the locale used for locale-specific formatting (public member function) | | out | returns the iterator to output buffer (public member function) | | advance\_to | advances the output iterator to the given position (public member function) | std::basic\_format\_context::arg --------------------------------- | | | | | --- | --- | --- | | ``` std::basic_format_arg<basic_format_context> arg( std::size_t id ) const; ``` | | | Returns a `std::basic_format_arg` holding the `id`-th argument in `args`, where `args` is the parameter pack or `std::basic_format_args` object passed to the formatting function. If `id` is not less than the number of formatting arguments, returns a default-constructed `std::basic_format_arg` (holding a `[std::monostate](../variant/monostate "cpp/utility/variant/monostate")` object). std::basic\_format\_context::locale ------------------------------------ | | | | | --- | --- | --- | | ``` std::locale locale(); ``` | | | Returns the locale passed to the formatting function, or a default-constructed `[std::locale](../../locale/locale "cpp/locale/locale")` if the formatting function does not take a locale. std::basic\_format\_context::out --------------------------------- | | | | | --- | --- | --- | | ``` iterator out(); ``` | | | Returns the iterator to the output buffer. The result is move-constructed from the stored iterator. std::basic\_format\_context::advance\_to ----------------------------------------- | | | | | --- | --- | --- | | ``` void advance_to( iterator it ); ``` | | | Move assigns `it` to the stored output iterator. After a call to `advance_to`, the next call to `out()` will return an iterator with the value that `it` had before the assignment. ### Example ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 3567](https://cplusplus.github.io/LWG/issue3567) | C++20 | `basic_format_context` does not work move-only iterator types | made to move iterators | ### See also cpp std::format_error std::format\_error ================== | Defined in header `[<format>](../../header/format "cpp/header/format")` | | | | --- | --- | --- | | ``` class format_error; ``` | | (since C++20) | Defines the type of exception object thrown to report errors in the formatting library. ![std-format error-inheritance.svg]() Inheritance diagram. ### Member functions | | | | --- | --- | | (constructor) | constructs a new `format_error` object with the given message (public member function) | | operator= | replaces the `format_error` object (public member function) | | what | returns the explanatory string (public member function) | std::format\_error::format\_error ---------------------------------- | | | | | --- | --- | --- | | ``` format_error( const std::string& what_arg ); ``` | (1) | (since C++20) | | ``` format_error( const char* what_arg ); ``` | (2) | (since C++20) | | ``` format_error( const format_error& other ) noexcept; ``` | (3) | (since C++20) | 1-2) Constructs the exception object with `what_arg` as explanatory string that can be accessed through [`what()`](../../error/exception/what "cpp/error/exception/what"). 3) Copy constructor. If `*this` and `other` both have dynamic type `std::format_error` then `[std::strcmp](http://en.cppreference.com/w/cpp/string/byte/strcmp)(what(), other.what()) == 0`. ### Parameters | | | | | --- | --- | --- | | what\_arg | - | explanatory string | | other | - | another exception object to copy | ### Exceptions 1-2) May throw `[std::bad\_alloc](../../memory/new/bad_alloc "cpp/memory/new/bad alloc")` ### Notes Because copying `std::format_error` is not permitted to throw exceptions, this message is typically stored internally as a separately-allocated reference-counted string. This is also why there is no constructor taking `std::string&&`: it would have to copy the content anyway. std::format\_error::operator= ------------------------------ | | | | | --- | --- | --- | | ``` format_error& operator=( const format_error& other ) noexcept; ``` | | (since C++20) | Assigns the contents with those of `other`. If `*this` and `other` both have dynamic type `std::format_error` then `[std::strcmp](http://en.cppreference.com/w/cpp/string/byte/strcmp)(what(), other.what()) == 0` after assignment. ### Parameters | | | | | --- | --- | --- | | other | - | another exception object to assign with | ### Return value `*this`. std::format\_error::what ------------------------- | | | | | --- | --- | --- | | ``` virtual const char* what() const noexcept; ``` | | (since C++20) | Returns the explanatory string. ### Parameters (none). ### Return value Pointer to a null-terminated string with explanatory information. The string is suitable for conversion and display as a `[std::wstring](../../string/basic_string "cpp/string/basic string")`. The pointer is guaranteed to be valid at least until the exception object from which it is obtained is destroyed, or until a non-const member function (e.g. copy assignment operator) on the exception object is called. ### Notes Implementations are allowed but not required to override `what()`. Inherited from [std::runtime\_error](../../error/runtime_error "cpp/error/runtime error") ------------------------------------------------------------------------------------------- Inherited from [std::exception](../../error/exception "cpp/error/exception") ------------------------------------------------------------------------------ ### Member functions | | | | --- | --- | | [(destructor)](../../error/exception/~exception "cpp/error/exception/~exception") [virtual] | destroys the exception object (virtual public member function of `std::exception`) | | [what](../../error/exception/what "cpp/error/exception/what") [virtual] | returns an explanatory string (virtual public member function of `std::exception`) | ### Example ### See also cpp std::format_to std::format\_to =============== | Defined in header `[<format>](../../header/format "cpp/header/format")` | | | | --- | --- | --- | | ``` template< class OutputIt, class... Args > OutputIt format_to( OutputIt out, std::format_string<Args...> fmt, Args&&... args ); ``` | (1) | (since C++20) | | ``` template< class OutputIt, class... Args > OutputIt format_to( OutputIt out, std::wformat_string<Args...> fmt, Args&&... args ); ``` | (2) | (since C++20) | | ``` template< class OutputIt, class... Args > OutputIt format_to( OutputIt out, const std::locale& loc, std::format_string<Args...> fmt, Args&&... args ); ``` | (3) | (since C++20) | | ``` template< class OutputIt, class... Args > OutputIt format_to( OutputIt out, const std::locale& loc, std::wformat_string<Args...> fmt, Args&&... args ); ``` | (4) | (since C++20) | Format `args` according to the format string `fmt`, and write the result to the output iterator `out`. If present, `loc` is used for locale-specific formatting. 1) equivalent to `return [std::vformat\_to](http://en.cppreference.com/w/cpp/utility/format/vformat_to)(out, fmt.str, [std::make\_format\_args](http://en.cppreference.com/w/cpp/utility/format/make_format_args)(args...));` 2) equivalent to `return [std::vformat\_to](http://en.cppreference.com/w/cpp/utility/format/vformat_to)(std::move(out), fmt.str, [std::make\_wformat\_args](http://en.cppreference.com/w/cpp/utility/format/make_format_args)(args...));` 3) equivalent to `return [std::vformat\_to](http://en.cppreference.com/w/cpp/utility/format/vformat_to)(out, loc, fmt.str, [std::make\_format\_args](http://en.cppreference.com/w/cpp/utility/format/make_format_args)(args...));` 4) equivalent to `return [std::vformat\_to](http://en.cppreference.com/w/cpp/utility/format/vformat_to)(std::move(out), loc, fmt.str, [std::make\_wformat\_args](http://en.cppreference.com/w/cpp/utility/format/make_format_args)(args...));` Let `CharT` be `char` for overloads (1,3), `wchar_t` for overloads (2,4). These overloads participate in overload resolution only if `OutputIt` satisfies the concept `[std::output\_iterator](http://en.cppreference.com/w/cpp/iterator/output_iterator)<const CharT&>`. The behavior is undefined if `OutputIt` does not model (meet the semantic requirements of) the concept `[std::output\_iterator](http://en.cppreference.com/w/cpp/iterator/output_iterator)<const CharT&>`, or if `[std::formatter](http://en.cppreference.com/w/cpp/utility/format/formatter)<Ti, CharT>` does not meet the [BasicFormatter](../../named_req/basicformatter "cpp/named req/BasicFormatter") requirements for any `Ti` in `Args` (as required by `[std::make\_format\_args](http://en.cppreference.com/w/cpp/utility/format/make_format_args)` and `[std::make\_wformat\_args](http://en.cppreference.com/w/cpp/utility/format/make_format_args)`). ### Parameters | | | | | --- | --- | --- | | out | - | iterator to the output buffer | | fmt | - | an object that represents the format string. The format string consists of * ordinary characters (except `{` and `}`), which are copied unchanged to the output, * escape sequences `{{` and `}}`, which are replaced with `{` and `}` respectively in the output, and * replacement fields. Each replacement field has the following format: | | | | | --- | --- | --- | | `{` arg-id (optional) `}` | (1) | | | `{` arg-id (optional) `:` format-spec `}` | (2) | | 1) replacement field without a format specification 2) replacement field with a format specification | | | | | --- | --- | --- | | arg-id | - | specifies the index of the argument in `args` whose value is to be used for formatting; if it is omitted, the arguments are used in order. The arg-ids in a format string must all be present or all be omitted. Mixing manual and automatic indexing is an error. | | format-spec | - | the format specification defined by the `[std::formatter](formatter "cpp/utility/format/formatter")` specialization for the corresponding argument. | * For basic types and standard string types, the format specification is interpreted as [standard format specification](formatter#Standard_format_specification "cpp/utility/format/formatter"). * For chrono types, the format specification is interpreted as [chrono format specification](../../chrono/system_clock/formatter#Format_specification "cpp/chrono/system clock/formatter"). * For other formattable types, the format specification is determined by user-defined `formatter` specializations. | | args... | - | arguments to be formatted | | loc | - | `[std::locale](../../locale/locale "cpp/locale/locale")` used for locale-specific formatting | ### Return value Iterator past the end of the output range. ### Exceptions Propagates any exception thrown by formatter or iterator operations. ### Notes As of [P2216R3](https://wg21.link/P2216R3), it is an error if the format string is not a constant expression. `[std::vformat\_to](vformat_to "cpp/utility/format/vformat to")` can be used in this case. ### Example ``` #include <format> #include <iostream> #include <iterator> #include <string> auto main() -> int { std::string buffer; std::format_to( std::back_inserter(buffer), //< OutputIt "Hello, C++{}!\n", //< fmt "20"); //< arg std::cout << buffer; buffer.clear(); std::format_to( std::back_inserter(buffer), //< OutputIt "Hello, {0}::{1}!{2}", //< fmt "std", //< arg {0} "format_to()", //< arg {1} "\n", //< arg {2} "extra param(s)..."); //< unused std::cout << buffer; std::wstring wbuffer; std::format_to( std::back_inserter(wbuffer),//< OutputIt L"Hello, {2}::{1}!{0}", //< fmt L"\n", //< arg {0} L"format_to()", //< arg {1} L"std", //< arg {2} L"...is not..." //< unused L"...an error!"); //< unused std::wcout << wbuffer; } ``` Output: ``` Hello, C++20! Hello, std::format_to()! Hello, std::format_to()! ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [P2216R3](https://wg21.link/P2216R3) | C++20 | throws `[std::format\_error](format_error "cpp/utility/format/format error")` for invalid format string | invalid format string results in compile-time error | | [P2418R2](https://wg21.link/P2418R2) | C++20 | objects that are neither const-usable nor copyable(such as generator-like objects) are not formattable | allow formatting these objects | | [P2508R1](https://wg21.link/P2508R1) | C++20 | there's no user-visible name for this facility | the name `basic_format_string` is exposed | ### See also | | | | --- | --- | | [format](format "cpp/utility/format/format") (C++20) | stores formatted representation of the arguments in a new string (function template) | | [format\_to\_n](format_to_n "cpp/utility/format/format to n") (C++20) | writes out formatted representation of its arguments through an output iterator, not exceeding specified size (function template) |
programming_docs
cpp std::formatter std::formatter ============== | Defined in header `[<format>](../../header/format "cpp/header/format")` | | | | --- | --- | --- | | ``` template< class T, class CharT = char > struct formatter; ``` | | (since C++20) | The enabled specializations of `formatter` define formatting rules for a given type. Enabled specializations meet the [Formatter](../../named_req/formatter "cpp/named req/Formatter") requirements. In particular, they define callables `parse` and `format`. For all types `T` and `CharT` for which no specialization `std::formatter<T, CharT>` is enabled, that specialization is a complete type and is disabled. Disabled specializations do not meet the [Formatter](../../named_req/formatter "cpp/named req/Formatter") requirements, and the following are all `false`: * `[std::is\_default\_constructible\_v](../../types/is_default_constructible "cpp/types/is default constructible")` * `[std::is\_copy\_constructible\_v](../../types/is_copy_constructible "cpp/types/is copy constructible")` * `[std::is\_move\_constructible\_v](../../types/is_move_constructible "cpp/types/is move constructible")` * `[std::is\_copy\_assignable\_v](../../types/is_copy_assignable "cpp/types/is copy assignable")` * `[std::is\_move\_assignable\_v](../../types/is_move_assignable "cpp/types/is move assignable")`. ### Standard specializations for basic types and string types In the following list, `CharT` is either `char` or `wchar_t`, `ArithmeticT` is any cv-unqualified arithmetic type other than `char`, `wchar_t`, `char8_t`, `char16_t`, or `char32_t`. | | | | | --- | --- | --- | | ``` template<> struct formatter<char, char>; template<> struct formatter<char, wchar_t>; template<> struct formatter<wchar_t, wchar_t>; template<> struct formatter<CharT*, CharT>; template<> struct formatter<const CharT*, CharT>; template<std::size_t N> struct formatter<CharT[N], CharT>; template<std::size_t N> struct formatter<const CharT[N], CharT>; template<class Traits, class Alloc> struct formatter<std::basic_string<CharT, Traits, Alloc>, CharT>; template<class Traits> struct formatter<std::basic_string_view<CharT, Traits>, CharT>; template<> struct formatter<ArithmeticT, CharT>; template<> struct formatter<std::nullptr_t, CharT>; template<> struct formatter<void*, CharT>; template<> struct formatter<const void*, CharT>; ``` | | | Formatters for other pointers and pointers to members are disabled. Specializations such as `std::formatter<wchar_t, char>` and `std::formatter<const char*, wchar_t>` that would require encoding conversions are disabled. #### Standard format specification For basic types and string types, the format specification is based on the [format specification in Python](https://docs.python.org/3/library/string.html#formatspec). The syntax of format specifications is: | | | | | --- | --- | --- | | fill-and-align(optional) sign(optional) `#`(optional) `0`(optional) width(optional) precision(optional) `L`(optional) type(optional) | | | The sign, `#` and `0` options are only valid when an integer or floating-point presentation type is used. ##### fill and align fill-and-align is an optional *fill* character (which can be any character other than `{` or `}`), followed by one of the *align* options `<`, `>`, `^`. The meaning of *align* options is as follows: * `<`: Forces the field to be aligned to the start of the available space. This is the default when a non-integer non-floating-point presentation type is used. * `>`: Forces the field to be aligned to the end of the available space. This is the default when an integer or floating-point presentation type is used. * `^`: Forces the field to be centered within the available space by inserting ⌊n/2⌋ characters before and ⌈n/2⌉ characters after the value, where n is the total number of fill characters to insert. ``` char c = 120; auto s0 = std::format("{:6}", 42); // value of s0 is " 42" auto s1 = std::format("{:6}", 'x'); // value of s1 is "x " auto s2 = std::format("{:*<6}", 'x'); // value of s2 is "x*****" auto s3 = std::format("{:*>6}", 'x'); // value of s3 is "*****x" auto s4 = std::format("{:*^6}", 'x'); // value of s4 is "**x***" auto s5 = std::format("{:6d}", c); // value of s5 is " 120" auto s6 = std::format("{:6}", true); // value of s6 is "true " ``` ##### sign, #, and 0 The sign option can be one of following: * `+`: Indicates that a sign should be used for both non-negative and negative numbers. The `+` sign is inserted before the output value for non-negative numbers. * `-`: Indicates that a sign should be used for negative numbers only (this is the default behavior). * space: Indicates that a leading space should be used for non-negative numbers, and a minus sign for negative numbers. Negative zero is treated as a negative number. The sign option applies to floating-point infinity and NaN. ``` double inf = std::numeric_limits<double>::infinity(); double nan = std::numeric_limits<double>::quiet_NaN(); auto s0 = std::format("{0:},{0:+},{0:-},{0: }", 1); // value of s0 is "1,+1,1, 1" auto s1 = std::format("{0:},{0:+},{0:-},{0: }", -1); // value of s1 is "-1,-1,-1,-1" auto s2 = std::format("{0:},{0:+},{0:-},{0: }", inf); // value of s2 is "inf,+inf,inf, inf" auto s3 = std::format("{0:},{0:+},{0:-},{0: }", nan); // value of s3 is "nan,+nan,nan, nan" ``` The `#` option causes the *alternate form* to be used for the conversion. * For integral types, when binary, octal, or hexadecimal presentation type is used, the alternate form inserts the prefix (`0b`, `0`, or `0x`) into the output value after the sign character (possibly space) if there is one, or add it before the output value otherwise. * For floating-point types, the alternate form causes the result of the conversion of finite values to always contain a decimal-point character, even if no digits follow it. Normally, a decimal-point character appears in the result of these conversions only if a digit follows it. In addition, for `g` and `G` conversions, trailing zeros are not removed from the result. The `0` option pads the field with leading zeros (following any indication of sign or base) to the field width, except when applied to an infinity or NaN. If the `0` character and an *align* option both appear, the `0` character is ignored. ``` char c = 120; auto s1 = std::format("{:+06d}", c); // value of s1 is "+00120" auto s2 = std::format("{:#06x}", 0xa); // value of s2 is "0x000a" auto s3 = std::format("{:<06}", -42); // value of s3 is "-42 " // (0 is ignored because of < alignment) ``` ##### width and precision width is either a positive decimal number, or a nested replacement field (`{}` or `{`*n*`}`). If present, it specifies the minimum field width. precision is a dot (`.`) followed by either a non-negative decimal number or a nested replacement field. This field indicates the precision or maximum field size. It can only be used with floating-point and string types. For floating-point types, this field specifies the formatting precision. For string types, it provides an upper bound for the estimated width (see below) of the prefix of the string to be copied to the output. For a string in a Unicode encoding, the text to be copied to the output is the longest prefix of whole extended grapheme clusters whose estimated width is no greater than the precision. If a nested replacement field is used for width or precision, and the corresponding argument is not of integral type, or is negative, or is zero for width, an exception of type `[std::format\_error](format_error "cpp/utility/format/format error")` is thrown. ``` float pi = 3.14f; auto s1 = std::format("{:10f}", pi); // s1 = " 3.140000" (width = 10) auto s2 = std::format("{:{}f}", pi, 10); // s2 = " 3.140000" (width = 10) auto s3 = std::format("{:.5f}", pi); // s3 = "3.14000" (precision = 5) auto s4 = std::format("{:.{}f}", pi, 5); // s4 = "3.14000" (precision = 5) auto s5 = std::format("{:10.5f}", pi); // s5 = " 3.14000" // (width = 10, precision = 5) auto s6 = std::format("{:{}.{}f}", pi, 10, 5); // s6 = " 3.14000" // (width = 10, precision = 5) auto b1 = std::format("{:{}f}", pi, 10.0); // throws: width is not of integral type auto b2 = std::format("{:{}f}", pi, -10); // throws: width is negative auto b3 = std::format("{:.{}f}", pi, 5.0); // throws: precision is not of integral type ``` For string types, the width is defined as the estimated number of column positions appropriate for displaying it in a terminal. For the purpose of width computation, a string is assumed to be in a implementation-defined encoding. The method of width computation is unspecified, but for a string in a Unicode encoding, implementation should estimate the width of the string as the sum of estimated widths of the first code points in its extended grapheme clusters. The estimated width of a Unicode code point is 2 if the code point is within the following range, or 1 if it isn't: * U+1100 - U+115F * U+2329 - U+232A * U+2E80 - U+303E * U+3040 - U+A4CF * U+AC00 - U+D7A3 * U+F900 - U+FAFF * U+FE10 - U+FE19 * U+FE30 - U+FE6F * U+FF00 - U+FF60 * U+FFE0 - U+FFE6 * U+1F300 - U+1F64F * U+1F900 - U+1F9FF * U+20000 - U+2FFFD * U+30000 - U+3FFFD ``` auto s1 = std::format("{:.^5s}", "🐱"); // s1 = ".🐱.." auto s2 = std::format("{:.5s}", "🐱🐱🐱"); // s2 = "🐱🐱" auto s3 = std::format("{:.<5.5s}", "🐱🐱🐱"); // s3 = "🐱🐱." ``` ##### L (locale-specific formatting) The `L` option causes the locale-specific form to be used. This option is only valid for arithmetic types. * For integral types, the locale-specific form inserts the appropriate digit group separator characters according to the context's locale. * For floating-point types, the locale-specific form inserts the appropriate digit group and radix separator characters according to the context's locale. * For the textual representation of `bool`, the locale-specific form uses the appropriate string as if obtained with `[std::numpunct::truename](../../locale/numpunct/truefalsename "cpp/locale/numpunct/truefalsename")` or `[std::numpunct::falsename](../../locale/numpunct/truefalsename "cpp/locale/numpunct/truefalsename")`. ##### type The type option determines how the data should be presented. The available string presentation types are: * none, `s`: Copies the string to the output. The available integer presentation types for integral types other than `char`, `wchar_t`, and `bool` are: * `b`: Binary format. Produces the output as if by calling `[std::to\_chars](http://en.cppreference.com/w/cpp/utility/to_chars)(first, last, value, 2)`. The base prefix is `0b`. * `B`: same as `b`, except that the base prefix is `0B`. * `c`: Copies the character `static_cast<CharT>(value)` to the output, where `CharT` is the character type of the format string. Throws `[std::format\_error](format_error "cpp/utility/format/format error")` if value is not in the range of representable values for `CharT`. * `d`: Decimal format. Produces the output as if by calling `[std::to\_chars](http://en.cppreference.com/w/cpp/utility/to_chars)(first, last, value)`. * `o`: Octal format. Produces the output as if by calling `[std::to\_chars](http://en.cppreference.com/w/cpp/utility/to_chars)(first, last, value, 8)`. The base prefix is `0` if the corresponding argument value is nonzero and is empty otherwise. * `x`: Hex format. Produces the output as if by calling `[std::to\_chars](http://en.cppreference.com/w/cpp/utility/to_chars)(first, last, value, 16)`. The base prefix is `0x`. * `X`: same as `x`, except that it uses uppercase letters for digits above 9 and the base prefix is `0X`. * none: same as `d`. The available `char` and `wchar_t` presentation types are: * none, `c`: Copies the character to the output. * `b`, `B`, `d`, `o`, `x`, `X`: Uses integer presentation types. The available `bool` presentation types are: * none, `s`: Copies textual representation (`true` or `false`, or the locale-specific form) to the output. * `b`, `B`, `d`, `o`, `x`, `X`: Uses integer presentation types with the value `static_cast<unsigned char>(value)`. The available floating-point presentation types are: * `a`: If *precision* is specified, produces the output as if by calling `[std::to\_chars](http://en.cppreference.com/w/cpp/utility/to_chars)(first, last, value, std::chars\_format::hex, precision)` where `precision` is the specified precision; otherwise, the output is produced as if by calling `[std::to\_chars](http://en.cppreference.com/w/cpp/utility/to_chars)(first, last, value, std::chars\_format::hex)`. * `A`: same as `a`, except that it uses uppercase letters for digits above 9 and uses `P` to indicate the exponent. * `e`: Produces the output as if by calling `[std::to\_chars](http://en.cppreference.com/w/cpp/utility/to_chars)(first, last, value, std::chars\_format::scientific, precision)` where `precision` is the specified precision, or 6 if precision is not specified. * `E`: same as `e`, except that it uses `E` to indicate the exponent. * `f`, `F`: Produces the output as if by calling `[std::to\_chars](http://en.cppreference.com/w/cpp/utility/to_chars)(first, last, value, std::chars\_format::fixed, precision)` where `precision` is the specified precision, or 6 if precision is not specified. * `g`: Produces the output as if by calling `[std::to\_chars](http://en.cppreference.com/w/cpp/utility/to_chars)(first, last, value, std::chars\_format::general, precision)` where `precision` is the specified precision, or 6 if precision is not specified. * `G`: same as `g`, except that it uses `E` to indicate the exponent. * none: If *precision* is specified, produces the output as if by calling `[std::to\_chars](http://en.cppreference.com/w/cpp/utility/to_chars)(first, last, value, std::chars\_format::general, precision)` where `precision` is the specified precision; otherwise, the output is produced as if by calling `[std::to\_chars](http://en.cppreference.com/w/cpp/utility/to_chars)(first, last, value)`. For lower-case presentation types, infinity and NaN are formatted as `inf` and `nan`, respectively. For upper-case presentation types, infinity and NaN are formatted as `INF` and `NAN`, respectively. The available pointer presentation types (also used for `[std::nullptr\_t](../../types/nullptr_t "cpp/types/nullptr t")`) are: * none, `p`: If `[std::uintptr\_t](../../types/integer "cpp/types/integer")` is defined, produces the output as if by calling `[std::to\_chars](http://en.cppreference.com/w/cpp/utility/to_chars)(first, last, reinterpret\_cast<[std::uintptr\_t](http://en.cppreference.com/w/cpp/types/integer)>(value), 16)` with the prefix `0x` added to the output; otherwise, the output is implementation-defined. ### Standard specializations for library types | | | | --- | --- | | [std::formatter<std::chrono::duration>](../../chrono/duration/formatter "cpp/chrono/duration/formatter") (C++20) | specialization of `std::formatter` that formats a `duration` according to the provided format (class template specialization) | | [std::formatter<std::chrono::sys\_time>](../../chrono/system_clock/formatter "cpp/chrono/system clock/formatter") (C++20) | specialization of `std::formatter` that formats a `sys_time` according to the provided format (class template specialization) | | [std::formatter<std::chrono::utc\_time>](../../chrono/utc_clock/formatter "cpp/chrono/utc clock/formatter") (C++20) | specialization of `std::formatter` that formats a `utc_time` according to the provided format (class template specialization) | | [std::formatter<std::chrono::tai\_time>](../../chrono/tai_clock/formatter "cpp/chrono/tai clock/formatter") (C++20) | specialization of `std::formatter` that formats a `tai_time` according to the provided format (class template specialization) | | [std::formatter<std::chrono::gps\_time>](../../chrono/gps_clock/formatter "cpp/chrono/gps clock/formatter") (C++20) | specialization of `std::formatter` that formats a `gps_time` according to the provided format (class template specialization) | | [std::formatter<std::chrono::file\_time>](../../chrono/file_clock/formatter "cpp/chrono/file clock/formatter") (C++20) | specialization of `std::formatter` that formats a `file_time` according to the provided format (class template specialization) | | [std::formatter<std::chrono::local\_time>](../../chrono/local_t/formatter "cpp/chrono/local t/formatter") (C++20) | specialization of `std::formatter` that formats a `local_time` according to the provided format (class template specialization) | | [std::formatter<std::chrono::day>](../../chrono/day/formatter "cpp/chrono/day/formatter") (C++20) | specialization of `std::formatter` that formats a `day` according to the provided format (class template specialization) | | [std::formatter<std::chrono::month>](../../chrono/month/formatter "cpp/chrono/month/formatter") (C++20) | specialization of `std::formatter` that formats a `month` according to the provided format (class template specialization) | | [std::formatter<std::chrono::year>](../../chrono/year/formatter "cpp/chrono/year/formatter") (C++20) | specialization of `std::formatter` that formats a `year` according to the provided format (class template specialization) | | [std::formatter<std::chrono::weekday>](../../chrono/weekday/formatter "cpp/chrono/weekday/formatter") (C++20) | specialization of `std::formatter` that formats a `weekday` according to the provided format (class template specialization) | | [std::formatter<std::chrono::weekday\_indexed>](../../chrono/weekday_indexed/formatter "cpp/chrono/weekday indexed/formatter") (C++20) | specialization of `std::formatter` that formats a `weekday_indexed` according to the provided format (class template specialization) | | [std::formatter<std::chrono::weekday\_last>](../../chrono/weekday_last/formatter "cpp/chrono/weekday last/formatter") (C++20) | specialization of `std::formatter` that formats a `weekday_last` according to the provided format (class template specialization) | | [std::formatter<std::chrono::month\_day>](../../chrono/month_day/formatter "cpp/chrono/month day/formatter") (C++20) | specialization of `std::formatter` that formats a `month_day` according to the provided format (class template specialization) | | [std::formatter<std::chrono::month\_day\_last>](../../chrono/month_day_last/formatter "cpp/chrono/month day last/formatter") (C++20) | specialization of `std::formatter` that formats a `month_day_last` according to the provided format (class template specialization) | | [std::formatter<std::chrono::month\_weekday>](../../chrono/month_weekday/formatter "cpp/chrono/month weekday/formatter") (C++20) | specialization of `std::formatter` that formats a `month_weekday` according to the provided format (class template specialization) | | [std::formatter<std::chrono::month\_weekday\_last>](../../chrono/month_weekday_last/formatter "cpp/chrono/month weekday last/formatter") (C++20) | specialization of `std::formatter` that formats a `month_weekday_last` according to the provided format (class template specialization) | | [std::formatter<std::chrono::year\_month>](../../chrono/year_month/formatter "cpp/chrono/year month/formatter") (C++20) | specialization of `std::formatter` that formats a `year_month` according to the provided format (class template specialization) | | [std::formatter<std::chrono::year\_month\_day>](../../chrono/year_month_day/formatter "cpp/chrono/year month day/formatter") (C++20) | specialization of `std::formatter` that formats a `year_month_day` according to the provided format (class template specialization) | | [std::formatter<std::chrono::year\_month\_day\_last>](../../chrono/year_month_day_last/formatter "cpp/chrono/year month day last/formatter") (C++20) | specialization of `std::formatter` that formats a `year_month_day_last` according to the provided format (class template specialization) | | [std::formatter<std::chrono::year\_month\_weekday>](../../chrono/year_month_weekday/formatter "cpp/chrono/year month weekday/formatter") (C++20) | specialization of `std::formatter` that formats a `year_month_weekday` according to the provided format (class template specialization) | | [std::formatter<std::chrono::year\_month\_weekday\_last>](../../chrono/year_month_weekday_last/formatter "cpp/chrono/year month weekday last/formatter") (C++20) | specialization of `std::formatter` that formats a `year_month_weekday_last` according to the provided format (class template specialization) | | [std::formatter<std::chrono::hh\_mm\_ss>](../../chrono/hh_mm_ss/formatter "cpp/chrono/hh mm ss/formatter") (C++20) | specialization of `std::formatter` that formats a `hh_mm_ss` according to the provided format (class template specialization) | | [std::formatter<std::chrono::sys\_info>](../../chrono/sys_info/formatter "cpp/chrono/sys info/formatter") (C++20) | specialization of `std::formatter` that formats a `sys_info` according to the provided format (class template specialization) | | [std::formatter<std::chrono::local\_info>](../../chrono/local_info/formatter "cpp/chrono/local info/formatter") (C++20) | specialization of `std::formatter` that formats a `local_info` according to the provided format (class template specialization) | | [std::formatter<std::chrono::zoned\_time>](../../chrono/zoned_time/formatter "cpp/chrono/zoned time/formatter") (C++20) | specialization of `std::formatter` that formats a `zoned_time` according to the provided format (class template specialization) | ### Example ``` #include <format> #include <iostream> // A wrapper for type T template<class T> struct Box { T value; }; // The wrapper Box<T> can be formatted using the format specification of the wrapped value template<class T, class CharT> struct std::formatter<Box<T>, CharT> : std::formatter<T, CharT> { // parse() is inherited from the base class // Define format() by calling the base class implementation with the wrapped value template<class FormatContext> auto format(Box<T> t, FormatContext& fc) const { return std::formatter<T, CharT>::format(t.value, fc); } }; int main() { Box<int> v = { 42 }; std::cout << std::format("{:#x}", v); } ``` Output: ``` 0x2a ``` ### See also | | | | --- | --- | | [basic\_format\_contextformat\_contextwformat\_context](basic_format_context "cpp/utility/format/basic format context") (C++20)(C++20)(C++20) | formatting state, including all formatting arguments and the output iterator (class template) |
programming_docs
cpp std::visit_format_arg std::visit\_format\_arg ======================= | Defined in header `[<format>](../../header/format "cpp/header/format")` | | | | --- | --- | --- | | ``` template< class Visitor, class Context > /* see below */ visit_format_arg( Visitor&& vis, std::basic_format_arg<Context> arg ); ``` | | (since C++20) | Applies the visitor `vis` to the object contained in `arg`. Equivalent to `[std::visit](http://en.cppreference.com/w/cpp/utility/variant/visit)([std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Visitor>(vis), value)`, where `value` is the `[std::variant](../variant "cpp/utility/variant")` stored in `arg`. ### Parameters | | | | | --- | --- | --- | | vis | - | a [Callable](../../named_req/callable "cpp/named req/Callable") that accepts every possible alternative from `arg` | | arg | - | a `[std::basic\_format\_arg](basic_format_arg "cpp/utility/format/basic format arg")` to be visited | ### Return value The value returned by the selected invocation of the visitor. ### Example ### See also | | | | --- | --- | | [make\_format\_argsmake\_wformat\_args](make_format_args "cpp/utility/format/make format args") (C++20)(C++20) | creates a type-erased object referencing all formatting arguments, convertible to format\_args (function template) | cpp std::basic_format_parse_context std::basic\_format\_parse\_context ================================== | Defined in header `[<format>](../../header/format "cpp/header/format")` | | | | --- | --- | --- | | ``` template< class CharT > class basic_format_parse_context; ``` | (1) | (since C++20) | | ``` using format_parse_context = basic_format_parse_context<char>; ``` | (2) | (since C++20) | | ``` using wformat_parse_context = basic_format_parse_context<wchar_t>; ``` | (3) | (since C++20) | Provides access to the format string parsing state consisting of the format string range being parsed and the argument counter for automatic indexing. A `basic_format_parse_context` instance is passed to [Formatter](../../named_req/formatter "cpp/named req/Formatter") when parsing the format specification. ### Member types | Type | Definition | | --- | --- | | `char_type` | `CharT` | | `iterator` | `[std::basic\_string\_view](http://en.cppreference.com/w/cpp/string/basic_string_view)<CharT>::const\_iterator` | | `const_iterator` | `[std::basic\_string\_view](http://en.cppreference.com/w/cpp/string/basic_string_view)<CharT>::const\_iterator` | ### Member functions | | | | --- | --- | | (constructor) | constructs a `std::basic_format_parse_context` instance from format string and argument count (public member function) | | operator= [deleted] | `std::basic_format_parse_context` is not copyable (public member function) | | begin | returns an iterator to the beginning of the format string range (public member function) | | end | returns an iterator to the end of the format string range (public member function) | | advance\_to | advances the begin iterator to the given position (public member function) | | next\_arg\_id | enters automatic indexing mode, and returns the next argument index (public member function) | | check\_arg\_id | enters manual indexing mode, checks if the given argument index is in range (public member function) | std::basic\_format\_parse\_context::basic\_format\_parse\_context ------------------------------------------------------------------ | | | | | --- | --- | --- | | ``` constexpr explicit basic_format_parse_context( std::basic_string_view<CharT> fmt, std::size_t num_args = 0 ) noexcept; ``` | (1) | | | ``` basic_format_parse_context(const basic_format_parse_context&) = delete; ``` | (2) | | 1) Constructs a `std::basic_format_parse_context` instance. Initializes the format string range to `[fmt.begin(), fmt.end())`, and the argument count to `num_args`. 2) The copy constructor is deleted. `std::basic_format_parse_context` is not copyable. std::basic\_format\_parse\_context::begin ------------------------------------------ | | | | | --- | --- | --- | | ``` constexpr const_iterator begin() const noexcept; ``` | | | Returns an iterator to the beginning of the format string range. std::basic\_format\_parse\_context::end ---------------------------------------- | | | | | --- | --- | --- | | ``` constexpr const_iterator end() const noexcept; ``` | | | Returns an iterator to the end of the format string range. std::basic\_format\_parse\_context::advance\_to ------------------------------------------------ | | | | | --- | --- | --- | | ``` constexpr void advance_to( const_iterator it ); ``` | | | Sets the beginning of the format string range to `it`. After a call to `advance_to`, subsequent calls to `begin()` will return a copy of `it`. The behavior is undefined if `end()` is not reachable from `it`. std::basic\_format\_parse\_context::next\_arg\_id -------------------------------------------------- | | | | | --- | --- | --- | | ``` constexpr std::size_t next_arg_id(); ``` | | | Enters automatic argument indexing mode, and returns the next argument index, starting from 0. If `*this` has already entered manual argument indexing mode, throws `[std::format\_error](format_error "cpp/utility/format/format error")`. std::basic\_format\_parse\_context::check\_arg\_id --------------------------------------------------- | | | | | --- | --- | --- | | ``` constexpr void check_arg_id( std::size_t id ); ``` | | | Enters manual argument indexing mode. If `*this` has already entered automatic argument indexing mode, throws `[std::format\_error](format_error "cpp/utility/format/format error")`. If `id` is larger than or equal to the argument count provided in the constructor, the call is not a constant expression. ### Example ### See also cpp std::formatted_size std::formatted\_size ==================== | Defined in header `[<format>](../../header/format "cpp/header/format")` | | | | --- | --- | --- | | ``` template< class... Args > std::size_t formatted_size( std::format_string<Args...> fmt, Args&&... args ); ``` | (1) | (since C++20) | | ``` template< class... Args > std::size_t formatted_size( std::wformat_string<Args...> fmt, Args&&... args ); ``` | (2) | (since C++20) | | ``` template< class... Args > std::size_t formatted_size( const std::locale& loc, std::format_string<Args...> fmt, Args&&... args ); ``` | (3) | (since C++20) | | ``` template< class... Args > std::size_t formatted_size( const std::locale& loc, std::wformat_string<Args...> fmt, Args&&... args ); ``` | (4) | (since C++20) | Determine the total number of characters in the formatted string by formatting `args` according to the format string `fmt`. If present, `loc` is used for locale-specific formatting. The behavior is undefined if `[std::formatter](http://en.cppreference.com/w/cpp/utility/format/formatter)<[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<Ti>, CharT>` does not meet the [BasicFormatter](../../named_req/basicformatter "cpp/named req/BasicFormatter") requirements for any `Ti` in `Args`. ### Parameters | | | | | | | | | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | fmt | - | an object that represents the format string. The format string consists of * ordinary characters (except `{` and `}`), which are copied unchanged to the output, * escape sequences `{{` and `}}`, which are replaced with `{` and `}` respectively in the output, and * replacement fields. Each replacement field has the following format: | | | | | --- | --- | --- | | `{` arg-id (optional) `}` | (1) | | | `{` arg-id (optional) `:` format-spec `}` | (2) | | 1) replacement field without a format specification 2) replacement field with a format specification | | | | | --- | --- | --- | | arg-id | - | specifies the index of the argument in `args` whose value is to be used for formatting; if it is omitted, the arguments are used in order. The arg-ids in a format string must all be present or all be omitted. Mixing manual and automatic indexing is an error. | | format-spec | - | the format specification defined by the `[std::formatter](formatter "cpp/utility/format/formatter")` specialization for the corresponding argument. | * For basic types and standard string types, the format specification is interpreted as [standard format specification](formatter#Standard_format_specification "cpp/utility/format/formatter"). * For chrono types, the format specification is interpreted as [chrono format specification](../../chrono/system_clock/formatter#Format_specification "cpp/chrono/system clock/formatter"). * For other formattable types, the format specification is determined by user-defined `formatter` specializations. | | args... | - | arguments to be formatted | | loc | - | `[std::locale](../../locale/locale "cpp/locale/locale")` used for locale-specific formatting | ### Return value The total number of characters in the formatted string. ### Exceptions Propagates any exception thrown by formatter. ### Example ``` #include <format> #include <iostream> #include <vector> #include <string_view> int main() { using namespace std::literals::string_view_literals; constexpr auto fmt_str { "Hubble's H{0} {1} {2:*^4} miles/sec/mpc."sv }; constexpr auto sub_zero { "₀"sv }; // { "\u2080"sv } => { 0xe2, 0x82, 0x80 }; constexpr auto aprox_equ { "≅"sv }; // { "\u2245"sv } => { 0xe2, 0x89, 0x85 }; constexpr int Ho { 42 }; // H₀ const auto min_buffer_size = std::formatted_size(fmt_str, sub_zero, aprox_equ, Ho); std::cout << "Min buffer size = " << min_buffer_size << '\n'; // Use std::vector as dynamic buffer. Note: buffer does not include the trailing '\0'. std::vector<char> buffer(min_buffer_size); std::format_to_n(buffer.data(), buffer.size(), fmt_str, sub_zero, aprox_equ, Ho); std::cout << "Buffer: \"" << std::string_view{buffer.data(), min_buffer_size} << "\"\n"; // Or we can print the buffer directly by adding the trailing '\0'. buffer.push_back('\0'); std::cout << "Buffer: \"" << buffer.data() << "\"\n"; } ``` Output: ``` Min buffer size = 37 Buffer: "Hubble's H₀ ≅ *42* miles/sec/mpc." Buffer: "Hubble's H₀ ≅ *42* miles/sec/mpc." ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [P2216R3](https://wg21.link/P2216R3) | C++20 | throws `[std::format\_error](format_error "cpp/utility/format/format error")` for invalid format string | invalid format string results in compile-time error | | [P2418R2](https://wg21.link/P2418R2) | C++20 | objects that are neither const-usable nor copyable(such as generator-like objects) are not formattable | allow formatting these objects | | [P2508R1](https://wg21.link/P2508R1) | C++20 | there's no user-visible name for this facility | the name `basic_format_string` is exposed | ### See also | | | | --- | --- | | [format\_to](format_to "cpp/utility/format/format to") (C++20) | writes out formatted representation of its arguments through an output iterator (function template) | | [format\_to\_n](format_to_n "cpp/utility/format/format to n") (C++20) | writes out formatted representation of its arguments through an output iterator, not exceeding specified size (function template) | cpp std::vformat_to std::vformat\_to ================ | Defined in header `[<format>](../../header/format "cpp/header/format")` | | | | --- | --- | --- | | ``` template< class OutputIt > OutputIt vformat_to( OutputIt out, std::string_view fmt, std::format_args args ); ``` | (1) | (since C++20) | | ``` template< class OutputIt > OutputIt vformat_to( OutputIt out, std::wstring_view fmt, std::wformat_args args ); ``` | (2) | (since C++20) | | ``` template< class OutputIt > OutputIt vformat_to( OutputIt out, const std::locale& loc, std::string_view fmt, std::format_args args ); ``` | (3) | (since C++20) | | ``` template< class OutputIt > OutputIt vformat_to( OutputIt out, const std::locale& loc, std::wstring_view fmt, std::wformat_args args ); ``` | (4) | (since C++20) | Format arguments held by `args` according to the format string `fmt`, and write the result to the output iterator `out`. If present, `loc` is used for locale-specific formatting. Let `CharT` be `decltype(fmt)::char_type` (`char` for overloads (1,3), `wchar_t` for overloads (2,4)). These overloads participate in overload resolution only if `OutputIt` satisfies the concept `[std::output\_iterator](http://en.cppreference.com/w/cpp/iterator/output_iterator)<const CharT&>`. The behavior is undefined if `OutputIt` does not model (meet the semantic requirements of) the concept `[std::output\_iterator](http://en.cppreference.com/w/cpp/iterator/output_iterator)<const CharT&>`, or if `[std::formatter](http://en.cppreference.com/w/cpp/utility/format/formatter)<Ti, CharT>` does not meet the [Formatter](../../named_req/formatter "cpp/named req/Formatter") requirements for any `Ti` in the type of arguments. ### Parameters | | | | | --- | --- | --- | | out | - | iterator to the output buffer | | fmt | - | an object that represents the format string. The format string consists of * ordinary characters (except `{` and `}`), which are copied unchanged to the output, * escape sequences `{{` and `}}`, which are replaced with `{` and `}` respectively in the output, and * replacement fields. Each replacement field has the following format: | | | | | --- | --- | --- | | `{` arg-id (optional) `}` | (1) | | | `{` arg-id (optional) `:` format-spec `}` | (2) | | 1) replacement field without a format specification 2) replacement field with a format specification | | | | | --- | --- | --- | | arg-id | - | specifies the index of the argument in `args` whose value is to be used for formatting; if it is omitted, the arguments are used in order. The arg-ids in a format string must all be present or all be omitted. Mixing manual and automatic indexing is an error. | | format-spec | - | the format specification defined by the `[std::formatter](formatter "cpp/utility/format/formatter")` specialization for the corresponding argument. | * For basic types and standard string types, the format specification is interpreted as [standard format specification](formatter#Standard_format_specification "cpp/utility/format/formatter"). * For chrono types, the format specification is interpreted as [chrono format specification](../../chrono/system_clock/formatter#Format_specification "cpp/chrono/system clock/formatter"). * For other formattable types, the format specification is determined by user-defined `formatter` specializations. | | args | - | arguments to be formatted | | loc | - | `[std::locale](../../locale/locale "cpp/locale/locale")` used for locale-specific formatting | ### Return value Iterator past the end of the output range. ### Exceptions Throws `[std::format\_error](format_error "cpp/utility/format/format error")` if `fmt` is not a valid format string for the provided arguments. Also propagates any exception thrown by formatter or iterator operations. ### Example ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [P2216R3](https://wg21.link/P2216R3) | C++20 | type of `args` is parameterized on `OutputIt` | not parameterized | ### See also cpp std::basic_format_args std::basic\_format\_args ======================== | Defined in header `[<format>](../../header/format "cpp/header/format")` | | | | --- | --- | --- | | ``` template< class Context > class basic_format_args; ``` | (1) | (since C++20) | | ``` using format_args = basic_format_args<std::format_context>; ``` | (2) | (since C++20) | | ``` using wformat_args = basic_format_args<std::wformat_context>; ``` | (3) | (since C++20) | Provides access to formatting arguments. ### Member functions | | | | --- | --- | | (constructor) | constructs a `basic_format_args` object (public member function) | | get | returns formatting argument at the given index (public member function) | std::basic\_format\_args::basic\_format\_args ---------------------------------------------- | | | | | --- | --- | --- | | ``` basic_format_args() noexcept; ``` | (1) | | | ``` template< class... Args > basic_format_args( const /*format-arg-store*/<Context, Args...>& store ) noexcept; ``` | (2) | | 1) Constructs a `basic_format_args` object that does not hold any formatting argument. 2) Constructs a `basic_format_args` object from the result of a call to `[std::make\_format\_args](make_format_args "cpp/utility/format/make format args")` or `[std::make\_wformat\_args](make_format_args "cpp/utility/format/make format args")`. `std::basic_format_args` has reference semantics. It is the programmer's responsibility to ensure that `*this` does not outlive `store` (which, in turn, should not outlive the arguments to `[std::make\_format\_args](make_format_args "cpp/utility/format/make format args")` or `[std::make\_wformat\_args](make_format_args "cpp/utility/format/make format args")`). std::basic\_format\_args::get ------------------------------ | | | | | --- | --- | --- | | ``` std::basic_format_arg<Context> get( std::size_t i ) const noexcept; ``` | | | Returns a `[std::basic\_format\_arg](basic_format_arg "cpp/utility/format/basic format arg")` holding the `i`-th argument in `args`, where `args` is the parameter pack passed to `[std::make\_format\_args](make_format_args "cpp/utility/format/make format args")` or `[std::make\_wformat\_args](make_format_args "cpp/utility/format/make format args")`. If there's no such formatting argument (i.e. `*this` was default-constructed or `i` is not less than the number of formatting arguments), returns a default-constructed `[std::basic\_format\_arg](basic_format_arg "cpp/utility/format/basic format arg")` (holding a `[std::monostate](../variant/monostate "cpp/utility/variant/monostate")` object). ### Example ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [P2216R3](https://wg21.link/P2216R3) | C++20 | `format_args_t` was provided due to overparameterization of `vformat_to` | removed | ### See also | | | | --- | --- | | [basic\_format\_arg](basic_format_arg "cpp/utility/format/basic format arg") (C++20) | class template that provides access to a formatting argument for user-defined formatters (class template) | cpp std::make_format_args, std::make_wformat_args std::make\_format\_args, std::make\_wformat\_args ================================================= | Defined in header `[<format>](../../header/format "cpp/header/format")` | | | | --- | --- | --- | | ``` template< class Context = std::format_context, class... Args > /*format-arg-store*/<Context, Args...> make_format_args( Args&&... args ); ``` | (1) | (since C++20) | | ``` template< class... Args > /*format-arg-store*/<std::wformat_context, Args...> make_wformat_args( Args&&... args ); ``` | (2) | (since C++20) | Returns an object that stores an array of formatting arguments and can be implicitly converted to `[std::basic\_format\_args<Context>](basic_format_args "cpp/utility/format/basic format args")`. The behavior is undefined if `typename Context::template formatter_type<Ti>` does not meet the [BasicFormatter](../../named_req/basicformatter "cpp/named req/BasicFormatter") requirements for any `Ti` in `Args`. ### Parameters | | | | | --- | --- | --- | | args... | - | values to be used as formatting arguments | ### Returns An object that holds the formatting arguments. ### Notes A formatting argument has reference semantics for user-defined types and does not extend the lifetime of `args`. It is the programmer's responsibility to ensure that `args` outlive the return value. Usually, the result is only used as argument to formatting function. ### Example ``` #include <array> #include <format> #include <iostream> #include <string_view> void raw_write_to_log(std::string_view users_fmt, std::format_args&& args) { static int n{}; std::clog << std::format("{:04} : ", n++) << std::vformat(users_fmt, args) << '\n'; } template <typename... Args> constexpr void log(Args&&... args) { // Generate formatting string "{} "... std::array<char, sizeof...(Args) * 3 + 1> braces{}; constexpr const char c[4] = "{} "; for (auto i{0u}; i != braces.size() - 1; ++i) { braces[i] = c[i % 3]; } braces.back() = '\0'; raw_write_to_log(std::string_view{braces.data()}, std::make_format_args(args...)); } int main() { log("Number", "of", "arguments", "is", "arbitrary."); log("Any type that meets the `BasicFormatter` requirements", "can be printed."); log("For example:", 1, 2.0, '3', "*42*"); raw_write_to_log("{:02} │ {} │ {} │ {}", std::make_format_args(1, 2.0, '3', "4")); } ``` Output: ``` 0000 : Number of arguments is arbitrary. 0001 : Any type that meets the `BasicFormatter` requirements can be printed. 0002 : For example: 1 2.0 3 *42* 0003 : 01 │ 2.0 │ 3 │ 4 ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [P2418R2](https://wg21.link/P2418R2) | C++20 | objects that are neither const-usable nor copyable(such as generator-like objects) are not formattable | allow formatting these objects | ### See also | | | | --- | --- | | [basic\_format\_argsformat\_argswformat\_args](basic_format_args "cpp/utility/format/basic format args") (C++20)(C++20)(C++20) | class that provides access to all formatting arguments (class template) | | [vformat](vformat "cpp/utility/format/vformat") (C++20) | non-template variant of `[std::format](format "cpp/utility/format/format")` using type-erased argument representation (function) | | [vformat\_to](vformat_to "cpp/utility/format/vformat to") (C++20) | non-template variant of `[std::format\_to](format_to "cpp/utility/format/format to")` using type-erased argument representation (function template) |
programming_docs
cpp std::vformat std::vformat ============ | Defined in header `[<format>](../../header/format "cpp/header/format")` | | | | --- | --- | --- | | ``` std::string vformat( std::string_view fmt, std::format_args args ); ``` | (1) | (since C++20) | | ``` std::wstring vformat( std::wstring_view fmt, std::wformat_args args ); ``` | (2) | (since C++20) | | ``` std::string vformat( const std::locale& loc, std::string_view fmt, std::format_args args ); ``` | (3) | (since C++20) | | ``` std::wstring vformat( const std::locale& loc, std::wstring_view fmt, std::wformat_args args ); ``` | (4) | (since C++20) | Format arguments held by `args` according to the format string `fmt`, and return the result as a string. If present, `loc` is used for locale-specific formatting. ### Parameters | | | | | | | | | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | fmt | - | an object that represents the format string. The format string consists of * ordinary characters (except `{` and `}`), which are copied unchanged to the output, * escape sequences `{{` and `}}`, which are replaced with `{` and `}` respectively in the output, and * replacement fields. Each replacement field has the following format: | | | | | --- | --- | --- | | `{` arg-id (optional) `}` | (1) | | | `{` arg-id (optional) `:` format-spec `}` | (2) | | 1) replacement field without a format specification 2) replacement field with a format specification | | | | | --- | --- | --- | | arg-id | - | specifies the index of the argument in `args` whose value is to be used for formatting; if it is omitted, the arguments are used in order. The arg-ids in a format string must all be present or all be omitted. Mixing manual and automatic indexing is an error. | | format-spec | - | the format specification defined by the `[std::formatter](formatter "cpp/utility/format/formatter")` specialization for the corresponding argument. | * For basic types and standard string types, the format specification is interpreted as [standard format specification](formatter#Standard_format_specification "cpp/utility/format/formatter"). * For chrono types, the format specification is interpreted as [chrono format specification](../../chrono/system_clock/formatter#Format_specification "cpp/chrono/system clock/formatter"). * For other formattable types, the format specification is determined by user-defined `formatter` specializations. | | args | - | arguments to be formatted | | loc | - | `[std::locale](../../locale/locale "cpp/locale/locale")` used for locale-specific formatting | ### Return value A string object holding the formatted result. ### Exceptions Throws `[std::format\_error](format_error "cpp/utility/format/format error")` if `fmt` is not a valid format string for the provided arguments, or `[std::bad\_alloc](../../memory/new/bad_alloc "cpp/memory/new/bad alloc")` on allocation failure. Also propagates any exception thrown by formatter or iterator operations. ### Example ### See also cpp std::bad_variant_access std::bad\_variant\_access ========================= | Defined in header `[<variant>](../../header/variant "cpp/header/variant")` | | | | --- | --- | --- | | ``` class bad_variant_access : public std::exception ``` | | (since C++17) | `std::bad_variant_access` is the type of the exception thrown in the following situations: * [`std::get(std::variant)`](get "cpp/utility/variant/get") called with an index or type that does not match the currently active alternative * [`std::visit`](visit "cpp/utility/variant/visit") called to visit a variant that is [`valueless_by_exception`](valueless_by_exception "cpp/utility/variant/valueless by exception") ### Member functions | | | | --- | --- | | (constructor) | constructs a new `bad_variant_access` object (public member function) | | operator= | replaces the `bad_variant_access` object (public member function) | | what | returns the explanatory string (public member function) | std::bad\_variant\_access::bad\_variant\_access ------------------------------------------------ | | | | | --- | --- | --- | | ``` bad_variant_access() noexcept; ``` | (1) | (since C++17) | | ``` bad_variant_access( const bad_variant_access& other ) noexcept; ``` | (2) | (since C++17) | Constructs a new `bad_variant_access` object with an implementation-defined null-terminated byte string which is accessible through [`what()`](../../error/exception/what "cpp/error/exception/what"). 1) Default constructor. 2) Copy constructor. If `*this` and `other` both have dynamic type `std::bad_variant_access` then `[std::strcmp](http://en.cppreference.com/w/cpp/string/byte/strcmp)(what(), other.what()) == 0`. ### Parameters | | | | | --- | --- | --- | | other | - | another exception object to copy | std::bad\_variant\_access::operator= ------------------------------------- | | | | | --- | --- | --- | | ``` bad_variant_access& operator=( const bad_variant_access& other ) noexcept; ``` | | (since C++17) | Assigns the contents with those of `other`. If `*this` and `other` both have dynamic type `std::bad_variant_access` then `[std::strcmp](http://en.cppreference.com/w/cpp/string/byte/strcmp)(what(), other.what()) == 0` after assignment. ### Parameters | | | | | --- | --- | --- | | other | - | another exception object to assign with | ### Return value `*this`. std::bad\_variant\_access::what -------------------------------- | | | | | --- | --- | --- | | ``` virtual const char* what() const noexcept; ``` | | (since C++17) | Returns the explanatory string. ### Parameters (none). ### Return value Pointer to a null-terminated string with explanatory information. The string is suitable for conversion and display as a `[std::wstring](../../string/basic_string "cpp/string/basic string")`. The pointer is guaranteed to be valid at least until the exception object from which it is obtained is destroyed, or until a non-const member function (e.g. copy assignment operator) on the exception object is called. ### Notes Implementations are allowed but not required to override `what()`. Inherited from [std::exception](../../error/exception "cpp/error/exception") ------------------------------------------------------------------------------ ### Member functions | | | | --- | --- | | [(destructor)](../../error/exception/~exception "cpp/error/exception/~exception") [virtual] | destroys the exception object (virtual public member function of `std::exception`) | | [what](../../error/exception/what "cpp/error/exception/what") [virtual] | returns an explanatory string (virtual public member function of `std::exception`) | ### Example ``` #include <variant> #include <iostream> int main() { std::variant<int, float> v; v = 12; try { std::get<float>(v); } catch(const std::bad_variant_access& e) { std::cout << e.what() << '\n'; } } ``` Possible output: ``` bad_variant_access ``` ### See also | | | | --- | --- | | [std::get(std::variant)](get "cpp/utility/variant/get") (C++17) | reads the value of the variant given the index or the type (if the type is unique), throws on error (function template) | | [visit](visit "cpp/utility/variant/visit") (C++17) | calls the provided functor with the arguments held by one or more variants (function template) | cpp std::variant_size, std::variant_size_v std::variant\_size, std::variant\_size\_v ========================================= | Defined in header `[<variant>](../../header/variant "cpp/header/variant")` | | | | --- | --- | --- | | ``` template <class T> struct variant_size; /* undefined */ ``` | (1) | (since C++17) | | ``` template <class... Types> struct variant_size<std::variant<Types...>> : std::integral_constant<std::size_t, sizeof...(Types)> { }; ``` | (2) | (since C++17) | | ``` template <class T> class variant_size<const T>; ``` | (3) | (since C++17) | | ``` template <class T> class variant_size<volatile T>; template <class T> class variant_size<const volatile T>; ``` | (3) | (since C++17) (deprecated in C++20) | Provides access to the number of alternatives in a possibly cv-qualified variant as a compile-time constant expression. Formally, 2) meets the [UnaryTypeTrait](../../named_req/unarytypetrait "cpp/named req/UnaryTypeTrait") requirements with a base characteristic of `std::integral_constant<std::size_t, sizeof...(Types)>` 3) meets the [UnaryTypeTrait](../../named_req/unarytypetrait "cpp/named req/UnaryTypeTrait") requirements with a base characteristic of `std::integral_constant<std::size_t, variant_size<T>>` ### Helper variable template | | | | | --- | --- | --- | | ``` template <class T> inline constexpr std::size_t variant_size_v = std::variant_size<T>::value; ``` | | (since C++17) | Inherited from [std::integral\_constant](../../types/integral_constant "cpp/types/integral constant") ------------------------------------------------------------------------------------------------------- ### Member constants | | | | --- | --- | | value [static] | `sizeof...(Types)` (public static member constant) | ### Member functions | | | | --- | --- | | operator std::size\_t | converts the object to `[std::size\_t](http://en.cppreference.com/w/cpp/types/size_t)`, returns `value` (public member function) | | operator() (C++14) | returns `value` (public member function) | ### Member types | Type | Definition | | --- | --- | | `value_type` | `std::size_t` | | `type` | `[std::integral\_constant](http://en.cppreference.com/w/cpp/types/integral_constant)<[std::size\_t](http://en.cppreference.com/w/cpp/types/size_t), value>` | ### Notes All specializations of `std::variant_size` satisfy [UnaryTypeTrait](../../named_req/unarytypetrait "cpp/named req/UnaryTypeTrait") with *base characteristic* `std::integral_constant<std::size_t, N>` for some `N`. ### Example ``` #include <any> #include <cstdio> #include <variant> static_assert(std::variant_size_v<std::variant<>> == 0); static_assert(std::variant_size_v<std::variant<int>> == 1); static_assert(std::variant_size_v<std::variant<int, int>> == 2); static_assert(std::variant_size_v<std::variant<int, int, int>> == 3); static_assert(std::variant_size_v<std::variant<int, float, double>> == 3); static_assert(std::variant_size_v<std::variant<std::monostate, void>> == 2); static_assert(std::variant_size_v<std::variant<const int, const float>> == 2); static_assert(std::variant_size_v<std::variant<std::variant<std::any>>> == 1); int main() { std::puts("All static assertions passed."); } ``` Output: ``` All static assertions passed. ``` ### See also | | | | --- | --- | | [variant\_alternativevariant\_alternative\_t](variant_alternative "cpp/utility/variant/variant alternative") (C++17) | obtains the type of the alternative specified by its index, at compile time (class template) (alias template) | | [std::tuple\_size<std::tuple>](../tuple/tuple_size "cpp/utility/tuple/tuple size") (C++11) | obtains the size of `tuple` at compile time (class template specialization) | cpp std::variant<Types...>::emplace std::variant<Types...>::emplace =============================== | | | | | --- | --- | --- | | | (1) | | | ``` template <class T, class... Args> T& emplace(Args&&... args); ``` | (since C++17) (until C++20) | | ``` template <class T, class... Args> constexpr T& emplace(Args&&... args); ``` | (since C++20) | | | (2) | | | ``` template <class T, class U, class... Args> T& emplace( std::initializer_list<U> il, Args&&... args ); ``` | (since C++17) (until C++20) | | ``` template <class T, class U, class... Args> constexpr T& emplace( std::initializer_list<U> il, Args&&... args ); ``` | (since C++20) | | | (3) | | | ``` template <std::size_t I, class... Args> std::variant_alternative_t<I, variant>& emplace( Args&&... args ); ``` | (since C++17) (until C++20) | | ``` template <std::size_t I, class... Args> constexpr std::variant_alternative_t<I, variant>& emplace( Args&&... args ); ``` | (since C++20) | | | (4) | | | ``` template <std::size_t I, class U, class... Args> std::variant_alternative_t<I, variant>& emplace( std::initializer_list<U> il, Args&&... args ); ``` | (since C++17) (until C++20) | | ``` template <std::size_t I, class U, class... Args> constexpr std::variant_alternative_t<I, variant>& emplace( std::initializer_list<U> il, Args&&... args ); ``` | (since C++20) | Creates a new value in-place, in an existing `variant` object. 1) Equivalent to `emplace<I>([std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Args>(args)...)`, where `I` is the zero-based index of `T` in `Types...`. * This overload participates in overload resolution only if `[std::is\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_constructible)<T, Args...>` is `true`, and `T` occurs exactly once in `Types...` 2) Equivalent to `emplace<I>(il, [std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Args>(args)...)`, where `I` is the zero-based index of `T` in `Types...`. * This overload participates in overload resolution only if `[std::is\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_constructible)<T, [std::initializer\_list](http://en.cppreference.com/w/cpp/utility/initializer_list)<U>&, Args...>` is `true`, and `T` occurs exactly once in `Types...` 3) First, destroys the currently contained value (if any). Then [direct-initializes](../../language/direct_initialization "cpp/language/direct initialization") the contained value as if constructing a value of type `T_I` with the arguments `[std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Args>(args)...`. If an exception is thrown, `*this` may become [valueless\_by\_exception](valueless_by_exception "cpp/utility/variant/valueless by exception"). * This overload participates in overload resolution only if `[std::is\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_constructible)<T_I, Args...>` is `true`. * It is a compile-time error if `I` is not less than `sizeof...(Types)`. 4) First, destroys the currently contained value (if any). Then [direct-initializes](../../language/direct_initialization "cpp/language/direct initialization") the contained value as if constructing a value of type `T_I` with the arguments `il, [std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Args>(args)...`. If an exception is thrown, `*this` may become [valueless\_by\_exception](valueless_by_exception "cpp/utility/variant/valueless by exception"). * This overload participates in overload resolution only if `[std::is\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_constructible)<T_I, [std::initializer\_list](http://en.cppreference.com/w/cpp/utility/initializer_list)<U>&, Args...>` is `true`. * It is a compile-time error if `I` is not less than `sizeof...(Types)`. ### Parameters | | | | | --- | --- | --- | | args | - | constructor arguments to use when constructing the new value | | il | - | initializer\_list argument to use when constructing the new value | ### Return value A reference to the new contained value. ### Exceptions 1-4) Any exception thrown during the initialization of the contained value. ### Example ``` #include <iostream> #include <string> #include <variant> int main() { std::variant<std::string> v1; v1.emplace<0>("abc"); // OK std::cout << std::get<0>(v1) << '\n'; v1.emplace<std::string>("def"); // OK std::cout << std::get<0>(v1) << '\n'; std::variant<std::string, std::string> v2; v2.emplace<1>("ghi"); // OK std::cout << std::get<1>(v2) << '\n'; // v2.emplace<std::string>("abc"); -> Error } ``` Output: ``` abc def ghi ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [P2231R1](https://wg21.link/P2231R1) | C++20 | `emplace` was not constexpr while the required operations can be constexpr in C++20 | made constexpr | ### See also | | | | --- | --- | | [operator=](operator= "cpp/utility/variant/operator=") | assigns a variant (public member function) | cpp std::variant<Types...>::index std::variant<Types...>::index ============================= | | | | | --- | --- | --- | | ``` constexpr std::size_t index() const noexcept; ``` | | (since C++17) | Returns the zero-based index of the alternative that is currently held by the variant. If the variant is [valueless\_by\_exception](valueless_by_exception "cpp/utility/variant/valueless by exception"), returns [variant\_npos](variant_npos "cpp/utility/variant/variant npos"). ### Example ``` #include <variant> #include <string> #include <iostream> int main() { std::variant<int, std::string> v = "abc"; std::cout << "v.index = " << v.index() << '\n'; v = {}; std::cout << "v.index = " << v.index() << '\n'; } ``` Output: ``` v.index = 1 v.index = 0 ``` ### See also | | | | --- | --- | | [holds\_alternative](holds_alternative "cpp/utility/variant/holds alternative") (C++17) | checks if a variant currently holds a given type (function template) | | [std::get(std::variant)](get "cpp/utility/variant/get") (C++17) | reads the value of the variant given the index or the type (if the type is unique), throws on error (function template) | cpp std::variant<Types...>::variant std::variant<Types...>::variant =============================== | | | | | --- | --- | --- | | ``` constexpr variant() noexcept(/* see below */); ``` | (1) | (since C++17) | | ``` constexpr variant( const variant& other ); ``` | (2) | (since C++17) | | ``` constexpr variant( variant&& other ) noexcept(/* see below */); ``` | (3) | (since C++17) | | ``` template< class T > constexpr variant( T&& t ) noexcept(/* see below */); ``` | (4) | (since C++17) | | ``` template< class T, class... Args > constexpr explicit variant( std::in_place_type_t<T>, Args&&... args ); ``` | (5) | (since C++17) | | ``` template< class T, class U, class... Args > constexpr explicit variant( std::in_place_type_t<T>, std::initializer_list<U> il, Args&&... args ); ``` | (6) | (since C++17) | | ``` template< std::size_t I, class... Args > constexpr explicit variant( std::in_place_index_t<I>, Args&&... args ); ``` | (7) | (since C++17) | | ``` template< std::size_t I, class U, class... Args > constexpr explicit variant( std::in_place_index_t<I>, std::initializer_list<U> il, Args&&... args ); ``` | (8) | (since C++17) | Constructs a new `variant` object. 1) Default constructor. Constructs a variant holding the [value-initialized](../../language/value_initialization "cpp/language/value initialization") value of the first alternative ([`index()`](index "cpp/utility/variant/index") is zero). * This constructor is `constexpr` if and only if the value initialization of the alternative type T\_0 would satisfy the requirements for a [constexpr function](../../language/constexpr "cpp/language/constexpr"). * This overload participates in overload resolution only if `[std::is\_default\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_default_constructible)<T_0>` is true. 2) Copy constructor. If `other` is not [valueless\_by\_exception](valueless_by_exception "cpp/utility/variant/valueless by exception"), constructs a variant holding the same alternative as `other` and [direct-initializes](../../language/direct_initialization "cpp/language/direct initialization") the contained value with `[std::get](http://en.cppreference.com/w/cpp/utility/variant/get)<other.index()>(other)`. Otherwise, initializes a valueless\_by\_exception variant. * This constructor is defined as deleted unless `[std::is\_copy\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_copy_constructible)<T_i>` is true for all `T_i` in `Types...`. * It is trivial if `[std::is\_trivially\_copy\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_copy_constructible)<T_i>` is true for all `T_i` in `Types...`. 3) Move constructor. If `other` is not [valueless\_by\_exception](valueless_by_exception "cpp/utility/variant/valueless by exception"), constructs a variant holding the same alternative as `other` and [direct-initializes](../../language/direct_initialization "cpp/language/direct initialization") the contained value with `[std::get](http://en.cppreference.com/w/cpp/utility/variant/get)<other.index()>(std::move(other))`. Otherwise, initializes a `valueless_by_exception` variant. * This overload participates in overload resolution only if `[std::is\_move\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_move_constructible)<T_i>` is true for all `T_i` in `Types...`. * It is trivial if `[std::is\_trivially\_move\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_move_constructible)<T_i>` is true for all `T_i` in `Types...`. 4) Converting constructor. Constructs a variant holding the alternative type `T_j` that would be selected by overload resolution for the expression `F([std::forward](http://en.cppreference.com/w/cpp/utility/forward)<T>(t))` if there was an overload of imaginary function `F(T_i)` for every `T_i` from `Types...` in scope at the same time, except that: * An overload `F(T_i)` is only considered if the declaration `T_i x[] = { [std::forward](http://en.cppreference.com/w/cpp/utility/forward)<T>(t) };` is valid for some invented variable `x`; [Direct-initializes](../../language/direct_initialization "cpp/language/direct initialization") the contained value as if by direct non-list-initialization from `[std::forward](http://en.cppreference.com/w/cpp/utility/forward)<T>(t)`. * This overload participates in overload resolution only if + `sizeof...(Types) > 0`, + `[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<U>` (until C++20)`[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<U>` (since C++20) is neither the same type as `variant`, nor a specialization of `[std::in\_place\_type\_t](../in_place "cpp/utility/in place")`, nor a specialization of `[std::in\_place\_index\_t](../in_place "cpp/utility/in place")`, + `[std::is\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_constructible)<T_j, T>` is `true`, + and the expression `F([std::forward](http://en.cppreference.com/w/cpp/utility/forward)<T>(t))` (with F being the above-mentioned set of imaginary functions) is well formed. * This constructor is a constexpr constructor if T\_j's selected constructor is a constexpr constructor. ``` std::variant<std::string> v("abc"); // OK std::variant<std::string, std::string> w("abc"); // ill-formed std::variant<std::string, const char*> x("abc"); // OK, chooses const char* std::variant<std::string, bool> y("abc"); // OK, chooses string; bool is not a candidate std::variant<float, long, double> z = 0; // OK, holds long // float and double are not candidates ``` 5) Constructs a variant with the specified alternative `T` and initializes the contained value with the arguments `[std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Args>(args)...`. * If T's selected constructor is a constexpr constructor, this constructor is also a constexpr constructor. * This overload participates in overload resolution only if there is exactly one occurrence of T in `Types...` and `[std::is\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_constructible)<T, Args...>` is `true`. 6) Constructs a variant with the specified alternative `T` and initializes the contained value with the arguments `il, [std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Args>(args)...`. * If T's selected constructor is a constexpr constructor, this constructor is also a constexpr constructor. * This overload participates in overload resolution only if there is exactly one occurrence of T in `Types...` and `[std::is\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_constructible)<T, initializer_list<U>&, Args...>` is `true`. 7) Constructs a variant with the alternative T\_i specified by the index `I` and initializes the contained value with the arguments `[std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Args>(args)...`. * If T\_i's selected constructor is a constexpr constructor, this constructor is also a constexpr constructor. * This overload participates in overload resolution only if `I < sizeof...(Types)` and `[std::is\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_constructible)<T_i, Args...>` is true. 8) Constructs a variant with the alternative T\_i specified by the index `I` and initializes the contained value with the arguments `il, [std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Args>(args)...`. * If T\_i's selected constructor is a constexpr constructor, this constructor is also a constexpr constructor. * This overload participates in overload resolution only if `I < sizeof...(Types)` and `[std::is\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_constructible)<T_i, [std::initializer\_list](http://en.cppreference.com/w/cpp/utility/initializer_list)<U>&, Args...>` is true. ### Parameters | | | | | --- | --- | --- | | other | - | another `variant` object whose contained value to copy/move | | t | - | value to initialize the contained value with | | args... | - | arguments to initialize the contained value with | | il | - | initializer list to initialize the contained value with | ### Exceptions 1) May throw any exception thrown by the value initialization of the first alternative. [`noexcept`](../../language/noexcept_spec "cpp/language/noexcept spec") specification: `noexcept([std::is\_nothrow\_default\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_default_constructible)<T_0>)` 2) May throw any exception thrown by direct-initializing any T\_i in `Types...` 3) May throw any exception thrown by move-constructing any T\_i in `Types...`. [`noexcept`](../../language/noexcept_spec "cpp/language/noexcept spec") specification: `noexcept( ([std::is\_nothrow\_move\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_move_constructible)<Types> && ...))` 4) May throw any exception thrown by the initialization of the selected alternative `T_j`. [`noexcept`](../../language/noexcept_spec "cpp/language/noexcept spec") specification: `noexcept([std::is\_nothrow\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_constructible)<T_j, T>)` 5-8) May throw any exception thrown by calling the selected constructor of the selected alternative ### Example ``` #include <cassert> #include <iostream> #include <string> #include <variant> #include <vector> template <class Os> Os& operator<< (Os& os, const std::vector<int>& v) { os << "{ "; for (int e: v) { std::cout << e << ' '; } return os << "}"; } int main() { { std::variant<int, std::string> var; // value-initializes first alternative assert(std::holds_alternative<int>(var) && var.index() == 0 && std::get<int>(var) == 0); } { std::variant<std::string, int> var{"STR"}; // initializes first alternative with std::string{"STR"}; assert(var.index() == 0); std::cout << "1) " << std::get<std::string>(var) << '\n'; } { std::variant<std::string, int> var{42}; // initializes second alternative with int = 42; assert(std::holds_alternative<int>(var)); std::cout << "2) " << std::get<int>(var) << '\n'; } { std::variant<std::string, std::vector<int>, float> var{ std::in_place_type<std::string>, 4, 'A'}; // initializes first alternative with std::string{4, 'A'}; assert(var.index() == 0); std::cout << "3) " << std::get<std::string>(var) << '\n'; } { std::variant<std::string, std::vector<int>, char> var{ std::in_place_type<std::vector<int>>, {1,2,3,4,5} }; // initializes second alternative with std::vector{1,2,3,4,5}; assert(var.index() == 1); std::cout << "4) " << std::get<std::vector<int>>(var) << '\n'; } { std::variant<std::string, std::vector<int>, bool> var{ std::in_place_index<0>, "ABCDE", 3}; // initializes first alternative with std::string{"ABCDE", 3}; assert(var.index() == 0); std::cout << "5) " << std::get<std::string>(var) << '\n'; } { std::variant<std::string, std::vector<int>, char> var{ std::in_place_index<1>, 4, 42}; // initializes second alternative with std::vector(4, 42); assert(std::holds_alternative<std::vector<int>>(var)); std::cout << "6) " << std::get<std::vector<int>>(var) << '\n'; } } ``` Output: ``` 1) STR 2) 42 3) AAAA 4) { 1 2 3 4 5 } 5) ABC 6) { 42 42 42 42 } ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 2901](https://cplusplus.github.io/LWG/issue2901) | C++17 | allocator-aware constructors provided but`variant` can't properly support allocators | constructors removed | | [P0739R0](https://wg21.link/p0739r0) | C++17 | converting constructor template interactspoorly with class template argument deduction | constraint added | | [LWG 3024](https://cplusplus.github.io/LWG/issue3024) | C++17 | copy constructor doesn't participate inoverload resolution if any member type is not copyable | defined as deleted instead | | [P0602R4](https://wg21.link/P0602R4) | C++17 | copy/move constructors may not betrivial even if underlying constructors are trivial | required to propagate triviality | | [P0608R3](https://wg21.link/P0608R3) | C++17 | converting constructor blindly assemblesan overload set, leading to unintended conversions | narrowing and boolean conversions not considered | | [P1957R2](https://wg21.link/P1957R2) | C++17 | converting constructor for `bool` did not allowimplicit conversion | Pointer to `bool` conversion is narrowing andconverting constructor has noexception for `bool` |
programming_docs
cpp std::variant<Types...>::valueless_by_exception std::variant<Types...>::valueless\_by\_exception ================================================ | | | | | --- | --- | --- | | ``` constexpr bool valueless_by_exception() const noexcept; ``` | | (since C++17) | Returns `false` if and only if the variant holds a value. ### Notes A variant may become valueless in the following situations: * (guaranteed) an exception is thrown during the move initialization of the contained value during [move assignment](operator= "cpp/utility/variant/operator=") * (optionally) an exception is thrown during the copy initialization of the contained value during [copy assignment](operator= "cpp/utility/variant/operator=") * (optionally) an exception is thrown when initializing the contained value during a type-changing [assignment](operator= "cpp/utility/variant/operator=") * (optionally) an exception is thrown when initializing the contained value during a type-changing [`emplace`](emplace "cpp/utility/variant/emplace") Since variant is never permitted to allocate dynamic memory, previous value cannot be retained in these situations. The situations marked "optionally" can be worked around by implementations that first construct the new value on the stack and then move it into the variant (provided non-throwing move). This applies even to variants of non-class types: ``` struct S { operator int() { throw 42; } }; std::variant<float, int> v{12.f}; // OK v.emplace<1>(S()); // v may be valueless ``` A variant that is valueless by exception is treated as being in an invalid state: [`index`](index "cpp/utility/variant/index") returns [`variant_npos`](variant_npos "cpp/utility/variant/variant npos"), [`get`](get "cpp/utility/variant/get") and [`visit`](visit "cpp/utility/variant/visit") throw [`bad_variant_access`](bad_variant_access "cpp/utility/variant/bad variant access"). ### Example ``` #include <cassert> #include <iostream> #include <stdexcept> #include <string> #include <variant> struct Demo { Demo(int) {} Demo(const Demo&) { throw std::domain_error("copy ctor"); } Demo& operator= (const Demo&) = default; }; int main() { std::variant<std::string, Demo> var{"str"}; assert(var.index() == 0); assert(std::get<0>(var) == "str"); assert(var.valueless_by_exception() == false); try { var = Demo{555}; } catch (const std::domain_error& ex) { std::cout << "1) Exception: " << ex.what() << '\n'; } assert(var.index() == std::variant_npos); assert(var.valueless_by_exception() == true); // Now the var is "valueless" which is an invalid state caused // by an exception raised in the process of type-changing assignment. try { std::get<1>(var); } catch (const std::bad_variant_access& ex) { std::cout << "2) Exception: " << ex.what() << '\n'; } var = "str2"; assert(var.index() == 0); assert(std::get<0>(var) == "str2"); assert(var.valueless_by_exception() == false); } ``` Possible output: ``` 1) Exception: copy ctor 2) Exception: std::get: variant is valueless ``` ### See also | | | | --- | --- | | [std::get(std::variant)](get "cpp/utility/variant/get") (C++17) | reads the value of the variant given the index or the type (if the type is unique), throws on error (function template) | | [index](index "cpp/utility/variant/index") | returns the zero-based index of the alternative held by the variant (public member function) | | [bad\_variant\_access](bad_variant_access "cpp/utility/variant/bad variant access") (C++17) | exception thrown on invalid accesses to the value of a variant (class) | cpp std::variant<Types...>::swap std::variant<Types...>::swap ============================ | | | | | --- | --- | --- | | ``` void swap( variant& rhs ) noexcept(/* see below */); ``` | | (since C++17) (until C++20) | | ``` constexpr void swap( variant& rhs ) noexcept(/* see below */); ``` | | (since C++20) | Swaps two `variant` objects. * if both `*this` and `rhs` are valueless by exception, does nothing * otherwise, if both `*this` and `rhs` hold the same alternative, calls `swap([std::get](http://en.cppreference.com/w/cpp/utility/variant/get)<i>(\*this), [std::get](http://en.cppreference.com/w/cpp/utility/variant/get)<i>(rhs))` where `i` is `index()`. If an exception is thrown, the state of the values depends on the exception safety of the swap function called. * otherwise, exchanges values of `rhs` and `*this`. If an exception is thrown, the state of `*this` and `rhs` depends on exception safety of variant's move constructor. The behavior is undefined unless lvalues of type `T_i` are [Swappable](../../named_req/swappable "cpp/named req/Swappable") and `[std::is\_move\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_move_constructible)<T_i>` is `true` for all `T_i` in `Types...`. ### Parameters | | | | | --- | --- | --- | | rhs | - | a `variant` object to swap with | ### Return value (none). ### Exceptions If `this->index() == rhs.index()`, may throw any exception thrown by `swap([std::get](http://en.cppreference.com/w/cpp/utility/variant/get)<i>(\*this), [std::get](http://en.cppreference.com/w/cpp/utility/variant/get)<i>(rhs))` with `i` being `index()`. Otherwise, may throw any exception thrown by the move constructors of the alternatives currently held by `*this` and `rhs`. [`noexcept`](../../language/noexcept_spec "cpp/language/noexcept spec") specification: `noexcept((([std::is\_nothrow\_move\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_move_constructible)<Types> && [std::is\_nothrow\_swappable\_v](http://en.cppreference.com/w/cpp/types/is_swappable)<Types>) && ...))` ### Example ``` #include <variant> #include <string> #include <iostream> int main() { std::variant<int, std::string> v1{2}, v2{"abc"}; std::visit([] (auto&& x) { std::cout << x << ' '; }, v1); std::visit([] (auto&& x) { std::cout << x << '\n'; }, v2); v1.swap(v2); std::visit([] (auto&& x) { std::cout << x << ' '; }, v1); std::visit([] (auto&& x) { std::cout << x << '\n'; }, v2); } ``` Output: ``` 2 abc abc 2 ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [P2231R1](https://wg21.link/P2231R1) | C++20 | `swap` was not constexpr while the required operations can be constexpr in C++20 | made constexpr | cpp std::get_if (std::variant) std::get\_if (std::variant) =========================== | Defined in header `[<variant>](../../header/variant "cpp/header/variant")` | | | | --- | --- | --- | | | (1) | (since C++17) | | ``` template< std::size_t I, class... Types > constexpr std::add_pointer_t<std::variant_alternative_t<I, std::variant<Types...>>> get_if( std::variant<Types...>* pv ) noexcept; ``` | | | ``` template< std::size_t I, class... Types > constexpr std::add_pointer_t<const std::variant_alternative_t<I, std::variant<Types...>>> get_if( const std::variant<Types...>* pv ) noexcept; ``` | | | | (2) | (since C++17) | | ``` template< class T, class... Types > constexpr std::add_pointer_t<T> get_if( std::variant<Types...>* pv ) noexcept; ``` | | | ``` template< class T, class... Types > constexpr std::add_pointer_t<const T> get_if( const std::variant<Types...>* pv ) noexcept; ``` | | 1) Index-based non-throwing accessor: If `pv` is not a null pointer and `pv->index() == I`, returns a pointer to the value stored in the variant pointed to by `pv`. Otherwise, returns a null pointer value. The call is ill-formed if `I` is not a valid index in the variant. 2) Type-based non-throwing accessor: Equivalent to (1) with `I` being the zero-based index of `T` in `Types...`. The call is ill-formed if `T` is not a unique element of `Types...`. ### Parameters | | | | | --- | --- | --- | | I | - | index to look up | | Type | - | unique type to look up | | pv | - | pointer to a variant | ### Return value Pointer to the value stored in the pointed-to variant or null pointer on error. ### Example ``` #include <variant> #include <iostream> int main() { auto check_value = [](const std::variant<int, float>& v) { if(const int* pval = std::get_if<int>(&v)) std::cout << "variant value: " << *pval << '\n'; else std::cout << "failed to get value!" << '\n'; }; std::variant<int, float> v{12}, w{3.f}; check_value(v); check_value(w); } ``` Output: ``` variant value: 12 failed to get value! ``` ### See also | | | | --- | --- | | [std::get(std::variant)](get "cpp/utility/variant/get") (C++17) | reads the value of the variant given the index or the type (if the type is unique), throws on error (function template) | cpp std::variant<Types...>::~variant std::variant<Types...>::~variant ================================ | | | | | --- | --- | --- | | ``` ~variant(); ``` | | (since C++17) (until C++20) | | ``` constexpr ~variant(); ``` | | (since C++20) | If [`valueless_by_exception()`](valueless_by_exception "cpp/utility/variant/valueless by exception") is `true`, does nothing. Otherwise, destroys the currently contained value. This destructor is trivial if `[std::is\_trivially\_destructible\_v](http://en.cppreference.com/w/cpp/types/is_destructible)<T_i>` is `true` for all `T_i` in `Types...`. ### Example ``` #include <variant> #include <cstdio> int main() { struct X { ~X() { puts("X::~X();"); } }; struct Y { ~Y() { puts("Y::~Y();"); } }; { puts("entering block #1"); std::variant<X,Y> var; puts("leaving block #1"); } { puts("entering block #2"); std::variant<X,Y> var{ std::in_place_index_t<1>{} }; // constructs var(Y) puts("leaving block #2"); } } ``` Output: ``` entering block #1 leaving block #1 X::~X(); entering block #2 leaving block #2 Y::~Y(); ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [P2231R1](https://wg21.link/P2231R1) | C++20 | the destructor was not constexpr while non-trivial destructors can be constexpr in C++20 | made constexpr | cpp std::variant_alternative, std::variant_alternative_t std::variant\_alternative, std::variant\_alternative\_t ======================================================= | Defined in header `[<variant>](../../header/variant "cpp/header/variant")` | | | | --- | --- | --- | | ``` template <std::size_t I, class T> struct variant_alternative; /* undefined */ ``` | (1) | (since C++17) | | ``` template <std::size_t I, class... Types> struct variant_alternative<I, variant<Types...>>; ``` | (2) | (since C++17) | | ``` template <std::size_t I, class T> class variant_alternative<I, const T>; ``` | (3) | (since C++17) | | ``` template <std::size_t I, class T> class variant_alternative<I, volatile T>; template <std::size_t I, class T> class variant_alternative<I, const volatile T>; ``` | (3) | (since C++17) (deprecated in C++20) | Provides compile-time indexed access to the types of the alternatives of the possibly cv-qualified variant, combining cv-qualifications of the variant (if any) with the cv-qualifications of the alternative. Formally, 2) meets the [TransformationTrait](../../named_req/transformationtrait "cpp/named req/TransformationTrait") requirements with a member typedef `type` equal to the type of the alternative with index `I` 3) meets the [TransformationTrait](../../named_req/transformationtrait "cpp/named req/TransformationTrait") requirements with a member typedef `type` that names, respectively, `[std::add\_const\_t](http://en.cppreference.com/w/cpp/types/add_cv)<std::variant\_alternative\_t<I,T>>`, `[std::add\_volatile\_t](http://en.cppreference.com/w/cpp/types/add_cv)<std::variant\_alternative\_t<I,T>>`, and `[std::add\_cv\_t](http://en.cppreference.com/w/cpp/types/add_cv)<std::variant\_alternative\_t<I,T>>` ### Member types | Member type | Definition | | --- | --- | | type | the type of `I`th alternative of the variant, where `I` must be in `[0, sizeof...(Types))`, otherwise the program is ill-formed. | ### Helper template alias | | | | | --- | --- | --- | | ``` template <size_t I, class T> using variant_alternative_t = typename variant_alternative<I, T>::type; ``` | | (since C++17) | ### Example ``` #include <variant> #include <iostream> using my_variant = std::variant<int, float>; static_assert(std::is_same_v <int, std::variant_alternative_t<0, my_variant>>); static_assert(std::is_same_v <float, std::variant_alternative_t<1, my_variant>>); // cv-qualification on the variant type propagates to the extracted alternative type. static_assert(std::is_same_v <const int, std::variant_alternative_t<0, const my_variant>>); int main() { std::cout << "All static assertions passed.\n"; } ``` Output: ``` All static assertions passed. ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 2974](https://cplusplus.github.io/LWG/issue2974) | C++17 | out-of-bounds index resulted in undefined behavior | made ill-formed | ### See also | | | | --- | --- | | [variant\_sizevariant\_size\_v](variant_size "cpp/utility/variant/variant size") (C++17) | obtains the size of the variant's list of alternatives at compile time (class template) (variable template) | | [std::tuple\_element<std::tuple>](../tuple/tuple_element "cpp/utility/tuple/tuple element") (C++11) | obtains the type of the specified element (class template specialization) | cpp std::swap(std::variant) std::swap(std::variant) ======================= | Defined in header `[<variant>](../../header/variant "cpp/header/variant")` | | | | --- | --- | --- | | ``` template <class... Types> void swap( std::variant<Types...>& lhs, std::variant<Types...>& rhs ) noexcept(/* see below */); ``` | | (since C++17) (until C++20) | | ``` template <class... Types> constexpr void swap( std::variant<Types...>& lhs, std::variant<Types...>& rhs ) noexcept(/* see below */); ``` | | (since C++20) | Overloads the `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` algorithm for `[std::variant](../variant "cpp/utility/variant")`. Effectively calls `lhs.swap(rhs)`. This overload participates in overload resolution only if `[std::is\_move\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_move_constructible)<T_i>` and `[std::is\_swappable\_v](http://en.cppreference.com/w/cpp/types/is_swappable)<T_i>` are both `true` for all `T_i` in `Types...` ### Parameters | | | | | --- | --- | --- | | lhs, rhs | - | `variant` objects whose values to swap | ### Return value (none). ### Exceptions [`noexcept`](../../language/noexcept_spec "cpp/language/noexcept spec") specification: `noexcept(noexcept(lhs.swap(rhs)))` ### Example ``` #include <variant> #include <string> #include <iostream> auto print = [](auto const& v, char term = '\n') { std::visit([](auto&& o) { std::cout << o; }, v); std::cout << term; }; int main() { std::variant<int, std::string> v1{123}, v2{"XYZ"}; print(v1, ' '); print(v2); std::swap(v1, v2); print(v1, ' '); print(v2); std::variant<double, std::string> v3{3.14}; // std::swap(v1, v3); // ERROR: ~ inconsistent parameter packs } ``` Output: ``` 123 XYZ XYZ 123 ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [P2231R1](https://wg21.link/P2231R1) | C++20 | `swap` was not constexpr while the required operations can be constexpr in C++20 | made constexpr | ### See also | | | | --- | --- | | [swap](swap "cpp/utility/variant/swap") | swaps with another variant (public member function) | cpp std::variant_npos std::variant\_npos ================== | Defined in header `[<variant>](../../header/variant "cpp/header/variant")` | | | | --- | --- | --- | | ``` inline constexpr std::size_t variant_npos = -1; ``` | | (since C++17) | This is a special value equal to the largest value representable by the type `std::size_t`, used as the return value of `index()` when `valueless_by_exception()` is `true`. ``` #include <iostream> #include <stdexcept> #include <string> #include <variant> struct Demon { Demon(int) {} Demon(const Demon&) { throw std::domain_error("copy ctor"); } Demon& operator= (const Demon&) = default; }; int main() { std::variant<int, Demon> var{42}; std::cout << std::boolalpha << "index == npos: " << (var.index() == std::variant_npos) << '\n'; try { var = Demon{666}; } catch (const std::domain_error& ex) { std::cout << "Exception: " << ex.what() << '\n' << "index == npos: " << (var.index() == std::variant_npos) << '\n' << "valueless: " << var.valueless_by_exception() << '\n'; } } ``` Possible output: ``` index == npos: false Exception: copy ctor index == npos: true valueless: true ``` ### See also | | | | --- | --- | | [index](index "cpp/utility/variant/index") | returns the zero-based index of the alternative held by the variant (public member function) | | [valueless\_by\_exception](valueless_by_exception "cpp/utility/variant/valueless by exception") | checks if the variant is in the invalid state (public member function) | cpp std::monostate std::monostate ============== | Defined in header `[<variant>](../../header/variant "cpp/header/variant")` | | | | --- | --- | --- | | ``` struct monostate { }; ``` | | (since C++17) | Unit type intended for use as a well-behaved empty alternative in `[std::variant](../variant "cpp/utility/variant")`. In particular, a variant of non-default-constructible types may list `std::monostate` as its first alternative: this makes the variant itself default-constructible. ### Member functions | | | | --- | --- | | (constructor) (implicitly declared) | trivial implicit default/copy/move constructor (public member function) | | (destructor) (implicitly declared) | trivial implicit destructor (public member function) | | operator= (implicitly declared) | trivial implicit copy/move assignment (public member function) | ### Non-member functions std::operator==, !=, <, <=, >, >=, <=>(std::monostate) ------------------------------------------------------- | | | | | --- | --- | --- | | ``` constexpr bool operator==(monostate, monostate) noexcept { return true; } ``` | | (since C++17) | | ``` constexpr bool operator!=(monostate, monostate) noexcept { return false; } constexpr bool operator<(monostate, monostate) noexcept { return false; } constexpr bool operator>(monostate, monostate) noexcept { return false; } constexpr bool operator<=(monostate, monostate) noexcept { return true; } constexpr bool operator>=(monostate, monostate) noexcept { return true; } ``` | | (since C++17) (until C++20) | | ``` constexpr std::strong_ordering operator<=>(monostate, monostate) noexcept { return std::strong_ordering::equal; } ``` | | (since C++20) | All instances of `std::monostate` compare equal. | | | | --- | --- | | The `<`, `<=`, `>`, `>=`, and `!=` operators are [synthesized](../../language/operators#Relational_operators "cpp/language/operators") from `operator<=>` and `operator==` respectively. | (since C++20) | ### Helper classes std::hash<std::monostate> -------------------------- | | | | | --- | --- | --- | | ``` template <> struct std::hash<monostate>; ``` | | | Specializes the `[std::hash](../hash "cpp/utility/hash")` algorithm for `std::monostate`. ### Example ``` #include <variant> #include <iostream> #include <cassert> struct S { S(int i) : i(i) {} int i; }; int main() { // Without the monostate type this declaration will fail. // This is because S is not default-constructible. std::variant<std::monostate, S> var; assert(var.index() == 0); try { std::get<S>(var); // throws! We need to assign a value } catch(const std::bad_variant_access& e) { std::cout << e.what() << '\n'; } var = 12; std::cout << std::get<S>(var).i << '\n'; } ``` Possible output: ``` std::get: wrong index for variant 12 ``` ### See also | | | | --- | --- | | [(constructor)](variant "cpp/utility/variant/variant") | constructs the variant object (public member function) |
programming_docs
cpp std::visit std::visit ========== | Defined in header `[<variant>](../../header/variant "cpp/header/variant")` | | | | --- | --- | --- | | ``` template <class Visitor, class... Variants> constexpr /*see below*/ visit( Visitor&& vis, Variants&&... vars ); ``` | (1) | (since C++17) | | ``` template <class R, class Visitor, class... Variants> constexpr R visit( Visitor&& vis, Variants&&... vars ); ``` | (2) | (since C++20) | Applies the visitor `vis` ([Callable](../../named_req/callable "cpp/named req/Callable") that can be called with any combination of types from variants) to the variants `vars`. These overloads participate in overload resolution only if every type in `[std::remove\_reference\_t](http://en.cppreference.com/w/cpp/types/remove_reference)<Variants>...` is a (possibly const-qualified) specialization of `[std::variant](../variant "cpp/utility/variant")`, or a (possibly const-qualified) class `C` such that there is exactly one `[std::variant](../variant "cpp/utility/variant")` specialization that is a base class of `C` and it is a public and unambiguous base class. Effectively returns. `[std::invoke](http://en.cppreference.com/w/cpp/utility/functional/invoke)([std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Visitor>(vis), [std::get](http://en.cppreference.com/w/cpp/utility/variant/get)<is>([std::forward](http://en.cppreference.com/w/cpp/utility/forward)<VariantBases>(vars))...)`. , where every type in `VariantBases...` is the unique `[std::variant](../variant "cpp/utility/variant")` specialization determined above, except that `const`, `&`, or `&&` is added to it if the corresponding argument is of a const-qualified type, is an lvalue, or is an rvalue, respectively, and `is...` is `[std::forward](http://en.cppreference.com/w/cpp/utility/forward)<VariantBases>(vars).index()...`. 1) The return type is deduced from the returned expression as if by `decltype`. The call is ill-formed if the invocation above is not a valid expression of the same type and value category, for all combinations of alternative types of all variants. 2) The return type is `R`. If `R` is (possibly cv-qualified) `void`, the result of the `invoke` expression is discarded. If `R` is a reference type and the implicit conversion from the result of the `[std::invoke](../functional/invoke "cpp/utility/functional/invoke")` call would [bind the returned reference to a temporary object](../../language/reference_initialization#Lifetime_of_a_temporary "cpp/language/reference initialization"), the program is ill-formed. (since C++23) ### Parameters | | | | | --- | --- | --- | | vis | - | a [Callable](../../named_req/callable "cpp/named req/Callable") that accepts every possible alternative from every variant | | vars | - | list of variants to pass to the visitor | ### Return value 1) The value returned by the selected invocation of the visitor. 2) Nothing if `R` is (possibly cv-qualified) `void`; otherwise the value returned by the selected invocation of the visitor, implicitly converted to `R`. ### Exceptions Throws `[std::bad\_variant\_access](bad_variant_access "cpp/utility/variant/bad variant access")` if any variant in `vars` is [`valueless_by_exception`](valueless_by_exception "cpp/utility/variant/valueless by exception"). Whether any variant is valueless by exception is determined as if by `([std::forward](http://en.cppreference.com/w/cpp/utility/forward)<VariantBases>(vars).valueless\_by\_exception() || ...)`. ### Complexity When the number of variants is zero or one, the invocation of the callable object is implemented in constant time, i.e. it does not depend on `sizeof...(Types)`. If the number of variants is larger than 1, the invocation of the callable object has no complexity requirements. ### Notes Let *n* be `(1 \* ... \* [std::variant\_size\_v](http://en.cppreference.com/w/cpp/utility/variant/variant_size)<[std::remove\_reference\_t](http://en.cppreference.com/w/cpp/types/remove_reference)<VariantBases>>)`, implementations usually generate a table equivalent to an (possibly multidimensional) array of *n* function pointers for every specialization of `std::visit`, which is similar to the implementation of [virtual functions](../../language/virtual "cpp/language/virtual"). Implementations may also generate a [switch statement](../../language/switch "cpp/language/switch") with *n* branches for `std::visit` (e.g. the MSVC STL implementation uses a switch statement when *n* is not greater than 256). On typical implementations, the time complexity of the invocation of `vis` can be considered equal to that of access to an element in an (possibly multidimensional) array or execution of a switch statement. ### Example ``` #include <iomanip> #include <iostream> #include <string> #include <type_traits> #include <variant> #include <vector> // the variant to visit using var_t = std::variant<int, long, double, std::string>; // helper constant for the visitor #3 template<class> inline constexpr bool always_false_v = false; // helper type for the visitor #4 template<class... Ts> struct overloaded : Ts... { using Ts::operator()...; }; // explicit deduction guide (not needed as of C++20) template<class... Ts> overloaded(Ts...) -> overloaded<Ts...>; int main() { std::vector<var_t> vec = {10, 15l, 1.5, "hello"}; for (auto& v: vec) { // 1. void visitor, only called for side-effects (here, for I/O) std::visit([](auto&& arg){std::cout << arg;}, v); // 2. value-returning visitor, demonstrates the idiom of returning another variant var_t w = std::visit([](auto&& arg) -> var_t {return arg + arg;}, v); // 3. type-matching visitor: a lambda that handles each type differently std::cout << ". After doubling, variant holds "; std::visit([](auto&& arg) { using T = std::decay_t<decltype(arg)>; if constexpr (std::is_same_v<T, int>) std::cout << "int with value " << arg << '\n'; else if constexpr (std::is_same_v<T, long>) std::cout << "long with value " << arg << '\n'; else if constexpr (std::is_same_v<T, double>) std::cout << "double with value " << arg << '\n'; else if constexpr (std::is_same_v<T, std::string>) std::cout << "std::string with value " << std::quoted(arg) << '\n'; else static_assert(always_false_v<T>, "non-exhaustive visitor!"); }, w); } for (auto& v: vec) { // 4. another type-matching visitor: a class with 3 overloaded operator()'s // Note: The `(auto arg)` template operator() will bind to `int` and `long` // in this case, but in its absence the `(double arg)` operator() // *will also* bind to `int` and `long` because both are implicitly // convertible to double. When using this form, care has to be taken // that implicit conversions are handled correctly. std::visit(overloaded { [](auto arg) { std::cout << arg << ' '; }, [](double arg) { std::cout << std::fixed << arg << ' '; }, [](const std::string& arg) { std::cout << std::quoted(arg) << ' '; } }, v); } } ``` Output: ``` 10. After doubling, variant holds int with value 20 15. After doubling, variant holds long with value 30 1.5. After doubling, variant holds double with value 3 hello. After doubling, variant holds std::string with value "hellohello" 10 15 1.500000 "hello" ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 3052](https://cplusplus.github.io/LWG/issue3052) | C++17 | the effects were unspecified if any type in `Variants` is not a `[std::variant](../variant "cpp/utility/variant")` | specified | ### See also | | | | --- | --- | | [swap](swap "cpp/utility/variant/swap") | swaps with another variant (public member function) | cpp operator==, !=, <, <=, >, >=, <=>(std::variant) operator==, !=, <, <=, >, >=, <=>(std::variant) =============================================== | Defined in header `[<variant>](../../header/variant "cpp/header/variant")` | | | | --- | --- | --- | | ``` template< class... Types > constexpr bool operator==( const std::variant<Types...>& v, const std::variant<Types...>& w ); ``` | (1) | (since C++17) | | ``` template< class... Types > constexpr bool operator!=( const std::variant<Types...>& v, const std::variant<Types...>& w ); ``` | (2) | (since C++17) | | ``` template< class... Types > constexpr bool operator<( const std::variant<Types...>& v, const std::variant<Types...>& w ); ``` | (3) | (since C++17) | | ``` template< class... Types > constexpr bool operator>( const std::variant<Types...>& v, const std::variant<Types...>& w ); ``` | (4) | (since C++17) | | ``` template< class... Types > constexpr bool operator<=( const std::variant<Types...>& v, const std::variant<Types...>& w ); ``` | (5) | (since C++17) | | ``` template< class... Types > constexpr bool operator>=( const std::variant<Types...>& v, const std::variant<Types...>& w ); ``` | (6) | (since C++17) | | ``` template< class... Types > constexpr std::common_comparison_category_t< std::compare_three_way_result_t<Types>...> operator<=>( const std::variant<Types...>& v, const std::variant<Types...>& w ); ``` | (7) | (since C++20) | 1) Equality operator for variants: * If `v.index() != w.index()`, returns `false`; * otherwise if `v.valueless_by_exception()`, returns `true`; * otherwise returns `[std::get](http://en.cppreference.com/w/cpp/utility/variant/get)<v.index()>(v) == [std::get](http://en.cppreference.com/w/cpp/utility/variant/get)<v.index()>(w)`. The behavior is undefined (until C++20)The program is ill-formed (since C++20) if `[std::get](http://en.cppreference.com/w/cpp/utility/variant/get)<i>(v) == [std::get](http://en.cppreference.com/w/cpp/utility/variant/get)<i>(w)` is not a valid expression returning a type convertible to bool, for any `i`. 2) Inequality operator for variants: * If `v.index() != w.index()`, returns `true`; * otherwise if `v.valueless_by_exception()`, returns `false`; * otherwise returns `[std::get](http://en.cppreference.com/w/cpp/utility/variant/get)<v.index()>(v) != [std::get](http://en.cppreference.com/w/cpp/utility/variant/get)<v.index()>(w)`. The behavior is undefined (until C++20)The program is ill-formed (since C++20) if `[std::get](http://en.cppreference.com/w/cpp/utility/variant/get)<i>(v) != [std::get](http://en.cppreference.com/w/cpp/utility/variant/get)<i>(w)` is not a valid expression returning a type convertible to bool, for any `i`. 3) Less-than operator for variants: * If `w.valueless_by_exception()`, returns `false`; * otherwise if `v.valueless_by_exception()`, returns `true`; * otherwise if `v.index() < w.index()`, returns `true`; * otherwise if `v.index() > w.index()`, returns `false`; * otherwise returns `[std::get](http://en.cppreference.com/w/cpp/utility/variant/get)<v.index()>(v) < [std::get](http://en.cppreference.com/w/cpp/utility/variant/get)<v.index()>(w)`. The behavior is undefined (until C++20)The program is ill-formed (since C++20) if `[std::get](http://en.cppreference.com/w/cpp/utility/variant/get)<i>(v) < [std::get](http://en.cppreference.com/w/cpp/utility/variant/get)<i>(w)` is not a valid expression returning a type convertible to bool, for any `i`. 4) Greater-than operator for variants: * If `v.valueless_by_exception()`, returns `false`; * otherwise if `w.valueless_by_exception()`, returns `true`; * otherwise if `v.index() > w.index()`, returns `true`; * otherwise if `v.index() < w.index()`, returns `false`; * otherwise returns `[std::get](http://en.cppreference.com/w/cpp/utility/variant/get)<v.index()>(v) > [std::get](http://en.cppreference.com/w/cpp/utility/variant/get)<v.index()>(w)`. The behavior is undefined (until C++20)The program is ill-formed (since C++20) if `[std::get](http://en.cppreference.com/w/cpp/utility/variant/get)<i>(v) > [std::get](http://en.cppreference.com/w/cpp/utility/variant/get)<i>(w)` is not a valid expression returning a type convertible to bool, for any `i`. 5) Less-equal operator for variants: * If `v.valueless_by_exception()`, returns `true`; * otherwise if `w.valueless_by_exception()`, returns `false`; * otherwise if `v.index() < w.index()`, returns `true`; * otherwise if `v.index() > w.index()`, returns `false`; * otherwise returns `[std::get](http://en.cppreference.com/w/cpp/utility/variant/get)<v.index()>(v) <= [std::get](http://en.cppreference.com/w/cpp/utility/variant/get)<v.index()>(w)`. The behavior is undefined (until C++20)The program is ill-formed (since C++20) if `[std::get](http://en.cppreference.com/w/cpp/utility/variant/get)<i>(v) <= [std::get](http://en.cppreference.com/w/cpp/utility/variant/get)<i>(w)` is not a valid expression returning a type convertible to bool, for any `i`. 6) Greater-equal operator for variants: * If `w.valueless_by_exception()`, returns `true`; * otherwise if `v.valueless_by_exception()`, returns `false`; * otherwise if `v.index() > w.index()`, returns `true`; * otherwise if `v.index() < w.index()`, returns `false`; * otherwise `[std::get](http://en.cppreference.com/w/cpp/utility/variant/get)<v.index()>(v) >= [std::get](http://en.cppreference.com/w/cpp/utility/variant/get)<v.index()>(w)`.The behavior is undefined (until C++20)The program is ill-formed (since C++20) if `[std::get](http://en.cppreference.com/w/cpp/utility/variant/get)<i>(v) >= [std::get](http://en.cppreference.com/w/cpp/utility/variant/get)<i>(w)` is not a valid expression returning a type convertible to bool, for any `i`. 7) Three-way comparison operator for variants: * If both `v.valueless_by_exception()` and `w.valueless_by_exception()` are `true`, returns `std::strong_ordering::equal`; * otherwise if `v.valueless_by_exception()` is `true`, returns `std::strong_ordering::less`; * otherwise if `w.valueless_by_exception()` is `true`, returns `std::strong_ordering::greater`; * otherwise if `v.index() != w.index()`, returns `v.index() <=> w.index()`; * otherwise equivalent to `[std::get](http://en.cppreference.com/w/cpp/utility/variant/get)<v.index()>(v) <=> [std::get](http://en.cppreference.com/w/cpp/utility/variant/get)<v.index()>(w)`. ### Parameters | | | | | --- | --- | --- | | v,w | - | variants to compare | ### Return value The result of the comparison as described above. ### Example ``` #include <iostream> #include <string> #include <variant> int main() { std::cout << std::boolalpha; std::string cmp; bool result; auto print2 = [&cmp, &result](const auto& lhs, const auto& rhs) { std::cout << lhs << ' ' << cmp << ' ' << rhs << " : " << result << '\n'; }; std::variant<int, std::string> v1, v2; std::cout << "operator==\n"; { cmp = "=="; // by default v1 = 0, v2 = 0; result = v1 == v2; // true std::visit(print2, v1, v2); v1 = v2 = 1; result = v1 == v2; // true std::visit(print2, v1, v2); v2 = 2; result = v1 == v2; // false std::visit(print2, v1, v2); v1 = "A"; result = v1 == v2; // false: v1.index == 1, v2.index == 0 std::visit(print2, v1, v2); v2 = "B"; result = v1 == v2; // false std::visit(print2, v1, v2); v2 = "A"; result = v1 == v2; // true std::visit(print2, v1, v2); } std::cout << "operator<\n"; { cmp = "<"; v1 = v2 = 1; result = v1 < v2; // false std::visit(print2, v1, v2); v2 = 2; result = v1 < v2; // true std::visit(print2, v1, v2); v1 = 3; result = v1 < v2; // false std::visit(print2, v1, v2); v1 = "A"; v2 = 1; result = v1 < v2; // false: v1.index == 1, v2.index == 0 std::visit(print2, v1, v2); v1 = 1; v2 = "A"; result = v1 < v2; // true: v1.index == 0, v2.index == 1 std::visit(print2, v1, v2); v1 = v2 = "A"; result = v1 < v2; // false std::visit(print2, v1, v2); v2 = "B"; result = v1 < v2; // true std::visit(print2, v1, v2); v1 = "C"; result = v1 < v2; // false std::visit(print2, v1, v2); } { std::variant<int, std::string> v1; std::variant<std::string, int> v2; // v1 == v2; // Compilation error: no known conversion } // TODO: C++20 three-way comparison operator <=> for variants } ``` Output: ``` operator== 0 == 0 : true 1 == 1 : true 1 == 2 : false A == 2 : false A == B : false A == A : true operator< 1 < 1 : false 1 < 2 : true 3 < 2 : false A < 1 : false 1 < A : true A < A : false A < B : true C < B : false ``` ### See also | | | | --- | --- | | [operator==operator!=operator<operator<=operator>operator>=operator<=>](../optional/operator_cmp "cpp/utility/optional/operator cmp") (C++17)(C++17)(C++17)(C++17)(C++17)(C++17)(C++20) | compares `optional` objects (function template) | cpp std::get (std::variant) std::get (std::variant) ======================= | Defined in header `[<variant>](../../header/variant "cpp/header/variant")` | | | | --- | --- | --- | | | (1) | (since C++17) | | ``` template< std::size_t I, class... Types > constexpr std::variant_alternative_t<I, std::variant<Types...>>& get( std::variant<Types...>& v ); ``` | | | ``` template< std::size_t I, class... Types > constexpr std::variant_alternative_t<I, std::variant<Types...>>&& get( std::variant<Types...>&& v ); ``` | | | ``` template< std::size_t I, class... Types > constexpr const std::variant_alternative_t<I, std::variant<Types...>>& get( const std::variant<Types...>& v ); ``` | | | ``` template< std::size_t I, class... Types > constexpr const std::variant_alternative_t<I, std::variant<Types...>>&& get( const std::variant<Types...>&& v ); ``` | | | | (2) | (since C++17) | | ``` template< class T, class... Types > constexpr T& get( std::variant<Types...>& v ); ``` | | | ``` template< class T, class... Types > constexpr T&& get( std::variant<Types...>&& v ); ``` | | | ``` template< class T, class... Types > constexpr const T& get( const std::variant<Types...>& v ); ``` | | | ``` template< class T, class... Types > constexpr const T&& get( const std::variant<Types...>&& v ); ``` | | 1) Index-based value accessor: If `v.index() == I`, returns a reference to the value stored in `v`. Otherwise, throws `[std::bad\_variant\_access](bad_variant_access "cpp/utility/variant/bad variant access")`. The call is ill-formed if `I` is not a valid index in the variant. 2) Type-based value accessor: If `v` holds the alternative `T`, returns a reference to the value stored in `v`. Otherwise, throws `[std::bad\_variant\_access](bad_variant_access "cpp/utility/variant/bad variant access")`. The call is ill-formed if `T` is not a unique element of `Types...`. ### Template parameters | | | | | --- | --- | --- | | I | - | index to look up | | T | - | unique type to look up | | Types... | - | types forming the `variant` | ### Parameters | | | | | --- | --- | --- | | v | - | a `variant` | ### Return value Reference to the value stored in the variant. ### Exceptions 1,2) Throws `[std::bad\_variant\_access](bad_variant_access "cpp/utility/variant/bad variant access")` on errors. ### Example ``` #include <variant> #include <string> #include <iostream> int main() { std::variant<int, float> v{12}, w; std::cout << std::get<int>(v) << '\n'; w = std::get<int>(v); w = std::get<0>(v); // same effect as the previous line // std::get<double>(v); // error: no double in [int, float] // std::get<3>(v); // error: valid index values are 0 and 1 try { w = 42.0f; std::cout << std::get<float>(w) << '\n'; // ok, prints 42 w = 42; std::cout << std::get<float>(w) << '\n'; // throws } catch (std::bad_variant_access const& ex) { std::cout << ex.what() << ": w contained int, not float\n"; } } ``` Possible output: ``` 12 42 Unexpected index: w contained int, not float ``` ### See also | | | | --- | --- | | [get\_if](get_if "cpp/utility/variant/get if") (C++17) | obtains a pointer to the value of a pointed-to variant given the index or the type (if unique), returns null on error (function template) | | [std::get(std::tuple)](../tuple/get "cpp/utility/tuple/get") (C++11) | tuple accesses specified element (function template) | | [std::get(std::array)](../../container/array/get "cpp/container/array/get") (C++11) | accesses an element of an `array` (function template) | | [std::get(std::pair)](../pair/get "cpp/utility/pair/get") (C++11) | accesses an element of a `pair` (function template) | | [get(std::ranges::subrange)](../../ranges/subrange/get "cpp/ranges/subrange/get") (C++20) | obtains iterator or sentinel from a `[std::ranges::subrange](../../ranges/subrange "cpp/ranges/subrange")` (function template) |
programming_docs
cpp std::holds_alternative std::holds\_alternative ======================= | Defined in header `[<variant>](../../header/variant "cpp/header/variant")` | | | | --- | --- | --- | | ``` template< class T, class... Types > constexpr bool holds_alternative( const std::variant<Types...>& v ) noexcept; ``` | | (since C++17) | Checks if the variant `v` holds the alternative `T`. The call is ill-formed if `T` does not appear exactly once in `Types...` ### Parameters | | | | | --- | --- | --- | | v | - | variant to examine | ### Return value `true` if the variant currently holds the alternative `T`, `false` otherwise. ### Example ``` #include <variant> #include <string> #include <iostream> int main() { std::variant<int, std::string> v = "abc"; std::cout << std::boolalpha << "variant holds int? " << std::holds_alternative<int>(v) << '\n' << "variant holds string? " << std::holds_alternative<std::string>(v) << '\n'; } ``` Output: ``` variant holds int? false variant holds string? true ``` ### See also | | | | --- | --- | | [index](index "cpp/utility/variant/index") | returns the zero-based index of the alternative held by the variant (public member function) | | [std::get(std::variant)](get "cpp/utility/variant/get") (C++17) | reads the value of the variant given the index or the type (if the type is unique), throws on error (function template) | cpp std::basic_stacktrace<Allocator>::size std::basic\_stacktrace<Allocator>::size ======================================= | | | | | --- | --- | --- | | ``` size_type size() const noexcept; ``` | | (since C++23) | Returns the number of entries in the stacktrace. ### Parameters (none). ### Return value The number of entries in the stacktrace. ### Complexity Constant. ### Example The following code uses `size` to display the number of entries in the current stacktrace: ``` #include <stacktrace> #include <iostream> int main() { auto trace = std::stacktrace::current(); std::cout << "trace contains " << trace.size() << " entries.\n"; } ``` Possible output: ``` trace contains 3 entries. ``` ### See also | | | | --- | --- | | [empty](empty "cpp/utility/basic stacktrace/empty") (C++23) | checks whether the `basic_stacktrace` is empty (public member function) | | [max\_size](max_size "cpp/utility/basic stacktrace/max size") (C++23) | returns the maximum possible number of stacktrace entries (public member function) | cpp std::basic_stacktrace<Allocator>::~basic_stacktrace std::basic\_stacktrace<Allocator>::~basic\_stacktrace ===================================================== | | | | | --- | --- | --- | | ``` ~basic_stacktrace(); ``` | | (since C++23) | Destructs the `basic_stacktrace`. The destructors of the `std::stacktrace_entry` objects it holds are called and the used storage is deallocated. ### Complexity Linear in the size of the `basic_stacktrace`. cpp std::basic_stacktrace<Allocator>::get_allocator std::basic\_stacktrace<Allocator>::get\_allocator ================================================= | | | | | --- | --- | --- | | ``` allocator_type get_allocator() const noexcept; ``` | | (since C++23) | Returns the allocator associated with the `basic_stacktrace`. ### Parameters (none). ### Return value The associated allocator. ### Complexity Constant. cpp std::operator<<(std::basic_stacktrace) std::operator<<(std::basic\_stacktrace) ======================================= | Defined in header `[<stacktrace>](../../header/stacktrace "cpp/header/stacktrace")` | | | | --- | --- | --- | | ``` template< class CharT, class Traits, class Allocator > std::basic_ostream<CharT, Traits>& operator<<( std::basic_ostream<CharT, Traits>& os, const std::basic_stacktrace<Allocator>& st ); ``` | | (since C++23) | Inserts the description of `st` into the output stream `os`. Equivalent to `return os << [std::to\_string](http://en.cppreference.com/w/cpp/string/basic_string/to_string)(st);`. ### Parameters | | | | | --- | --- | --- | | os | - | an output stream | | st | - | a `basic_stacktrace` whose description is to be inserted | ### Return value `os`. ### Exceptions May throw implementation-defined exceptions. ### Notes Since `[std::string](../../string/basic_string "cpp/string/basic string")` can only be outputted by `[std::ostream](../../io/basic_ostream "cpp/io/basic ostream")` (not by e.g. `[std::wostream](../../io/basic_ostream "cpp/io/basic ostream")`), it is effectively required that `os` be of type `[std::ostream](http://en.cppreference.com/w/cpp/io/basic_ostream)&`. ### Example ``` #include <stacktrace> #include <iostream> int main() { std::cout << "The stacktrace obtained in the main function:\n"; std::cout << std::stacktrace::current() << '\n'; []{ std::cout << "The stacktrace obtained in a nested lambda:\n"; std::cout << std::stacktrace::current() << '\n'; }(); } ``` Possible output: ``` The stacktrace obtained in the main function: 0# 0x0000000000402E7B in ./prog.exe 1# __libc_start_main in /lib/x86_64-linux-gnu/libc.so.6 2# 0x0000000000402CD9 in ./prog.exe The stacktrace obtained in a nested lambda: 0# 0x0000000000402DDA in ./prog.exe 1# 0x0000000000402EB2 in ./prog.exe 2# __libc_start_main in /lib/x86_64-linux-gnu/libc.so.6 3# 0x0000000000402CD9 in ./prog.exe ``` ### See also | | | | --- | --- | | [operator<<](../stacktrace_entry/operator_ltlt "cpp/utility/stacktrace entry/operator ltlt") (C++23) | performs stream output of `stacktrace_entry` (function template) | cpp std::basic_stacktrace<Allocator>::rbegin, std::basic_stacktrace<Allocator>::crbegin std::basic\_stacktrace<Allocator>::rbegin, std::basic\_stacktrace<Allocator>::crbegin ===================================================================================== | | | | | --- | --- | --- | | ``` const_reverse_iterator rbegin() const noexcept; ``` | (1) | (since C++23) | | ``` const_reverse_iterator crbegin() const noexcept; ``` | (2) | (since C++23) | Returns a reverse iterator to the first entry of the reversed `basic_stacktrace`. It corresponds to the last entry of the original `basic_stacktrace`. If the `basic_stacktrace` is empty, the returned iterator is equal to `rend()`. ![range-rbegin-rend.svg]() ### Parameters (none). ### Return value Reverse iterator to the first entry. ### Complexity Constant. ### Example ``` #include <algorithm> #include <iostream> #include <stacktrace> int main() { auto trace = std::stacktrace::current(); auto empty_trace = std::stacktrace{}; // Print stacktrace. std::for_each(trace.rbegin(), trace.rend(), [](const auto& f) { std::cout << f << '\n'; }); if (empty_trace.rbegin() == empty_trace.rend()) std::cout << "stacktrace 'empty_trace' is indeed empty.\n"; } ``` Possible output: ``` 0x0000000000402A29 in ./prog.exe __libc_start_main in /lib/x86_64-linux-gnu/libc.so.6 0x0000000000402BA5 in ./prog.exe stacktrace 'empty_trace' is indeed empty. ``` ### See also | | | | --- | --- | | [rendcrend](rend "cpp/utility/basic stacktrace/rend") (C++23) | returns a reverse iterator to the end (public member function) | cpp std::basic_stacktrace<Allocator>::at std::basic\_stacktrace<Allocator>::at ===================================== | | | | | --- | --- | --- | | ``` const_reference at( size_type pos ) const; ``` | | (since C++23) | Returns a reference to the entry at specified location `pos`, with bounds checking. If `pos` is not within the range of the stacktrace, an exception of type `[std::out\_of\_range](../../error/out_of_range "cpp/error/out of range")` is thrown. ### Parameters | | | | | --- | --- | --- | | pos | - | position of the stacktrace entry to return | ### Return value Reference to the requested entry. ### Exceptions `[std::out\_of\_range](../../error/out_of_range "cpp/error/out of range")` if `pos >= size()`. ### Complexity Constant. ### Example ### See also | | | | --- | --- | | [operator[]](operator_at "cpp/utility/basic stacktrace/operator at") (C++23) | access specified stacktrace entry (public member function) | cpp std::basic_stacktrace<Allocator>::basic_stacktrace std::basic\_stacktrace<Allocator>::basic\_stacktrace ==================================================== | | | | | --- | --- | --- | | ``` basic_stacktrace() noexcept(/* see below */); ``` | (1) | (since C++23) | | ``` explicit basic_stacktrace( const allocator_type& alloc ) noexcept; ``` | (2) | (since C++23) | | ``` basic_stacktrace( const basic_stacktrace& other ); ``` | (3) | (since C++23) | | ``` basic_stacktrace( basic_stacktrace&& other ) noexcept; ``` | (4) | (since C++23) | | ``` basic_stacktrace( const basic_stacktrace& other, const allocator_type& alloc ); ``` | (5) | (since C++23) | | ``` basic_stacktrace( basic_stacktrace&& other, const allocator_type& alloc ); ``` | (6) | (since C++23) | Constructs an empty `basic_stacktrace`, or copy/move from `other`. 1) Default constructor. Constructs an empty `basic_stacktrace` with a default-constructed allocator. 2) Constructs an empty `basic_stacktrace` using `alloc` as the allocator. 3) Copy constructor. Constructs a `basic_stacktrace` with the copy of the contents of `other`, the allocator is obtained as if by calling `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<allocator_type>::select\_on\_container\_copy\_construction(other.get\_allocator())`. 4) Move constructor. Constructs a `basic_stacktrace` with the contents of `other` using move semantics. Allocator is move-constructed from that of `other`. After construction, `other` is left in a valid but unspecified state. 5) Same as the copy constructor, except that `alloc` is used as the allocator. 6) Behaves same as the move constructor if `alloc == other.get_allocator()`. Otherwise, allocates memory with `alloc` and performs element-wise move. `alloc` is used as the allocator. (3,5,6) may throw an exception or construct an empty `basic_stacktrace` on allocation failure. ### Parameters | | | | | --- | --- | --- | | alloc | - | allocator to use for all memory allocations of the constructed `basic_stacktrace` | | other | - | another `basic_stacktrace` to copy/move from | ### Exceptions 1) [`noexcept`](../../language/noexcept_spec "cpp/language/noexcept spec") specification: `noexcept([std::is\_nothrow\_default\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_default_constructible)<allocator_type>)` 3,5,6) May propagate the exception thrown on allocation failure. ### Complexity 1-2) Constant. 3) Linear in size of `other`. 4) Constant. 5) Linear in size of `other`. 6) Linear in size of `other` if `alloc != other.get_allocator()`, otherwise constant. ### Notes After container move construction (overload (4)), references, pointers, and iterators (other than the end iterator) to `other` remain valid, but refer to elements that are now in `*this`. The current standard makes this guarantee via the blanket statement in [[container.requirements.general]/12](https://eel.is/c++draft/container.requirements.general#12), and a more direct guarantee is under consideration via [LWG 2321](https://cplusplus.github.io/LWG/issue2321). ### Example ### See also | | | | --- | --- | | [operator=](operator= "cpp/utility/basic stacktrace/operator=") (C++23) | assigns to the `basic_stacktrace` (public member function) | | [current](current "cpp/utility/basic stacktrace/current") [static] (C++23) | obtains the current stacktrace or its given part (public static member function) | cpp std::basic_stacktrace<Allocator>::current std::basic\_stacktrace<Allocator>::current ========================================== | | | | | --- | --- | --- | | ``` static basic_stacktrace current( const allocator_type& alloc = allocator_type() ) noexcept; ``` | (1) | (since C++23) | | ``` static basic_stacktrace current( size_type skip, const allocator_type& alloc = allocator_type() ) noexcept; ``` | (2) | (since C++23) | | ``` static basic_stacktrace current( size_type skip, size_type max_depth, const allocator_type& alloc = allocator_type() ) noexcept; ``` | (3) | (since C++23) | Let `s[i]` (0 ≤ `*i*` < `*n*`) denote the (`*i*+1`)-th stacktrace entry in the stacktrace of the current evaluation in the current thread of execution, where `*n*` is the count of the stacktrace entries in the stackentry. 1) Attempts to create a `basic_stacktrace` consisting of `s[0]`, `s[1]`, ..., `s[n - 1]`. 2) Attempts to create a `basic_stacktrace` consisting of `s[m]`, `s[m + 1]`, ..., `s[n - 1]`, where `*m*` is `min(skip, *n*)`. 3) Attempts to create a `basic_stacktrace` consisting of `s[m]`, `s[m + 1]`, ..., `s[o - 1]`, where `*m*` is `min(skip, *n*)` and `*o*` is `min(skip + max_depth, *n*)`. The behavior is undefined if the `skip + max_depth < skip` (i.e. the mathematical result of `skip + max_depth` overflows). In all cases, `alloc` is stored into the created `basic_stacktrace` and used to allocate the storage for stacktrace entries. ### Parameters | | | | | --- | --- | --- | | alloc | - | allocator to use for all memory allocations of the constructed `basic_stacktrace` | | skip | - | the number of stacktrace entries to skip | | max\_depth | - | the maximum depth of the stacktrace entries | ### Return value If the allocation succeeds, the `basic_stacktrace` described above. Otherwise, an empty `basic_stacktrace`. ### Example ### See also | | | | --- | --- | | [(constructor)](basic_stacktrace "cpp/utility/basic stacktrace/basic stacktrace") (C++23) | creates a new `basic_stacktrace` (public member function) | | [current](../source_location/current "cpp/utility/source location/current") [static] | constructs a new `source_location` corresponding to the location of the call site (public static member function of `std::source_location`) | cpp std::basic_stacktrace<Allocator>::operator[] std::basic\_stacktrace<Allocator>::operator[] ============================================= | | | | | --- | --- | --- | | ``` const_reference operator[]( size_type pos ) const; ``` | | (since C++23) | Returns a reference to the entry at specified location `pos`. No bounds checking is performed. If `pos` is not within the range of the stacktrace, i.e. `pos >= size()`, the behavior is undefined. ### Parameters | | | | | --- | --- | --- | | pos | - | position of the stacktrace entry to return | ### Return value Reference to the requested entry. ### Exceptions Throws nothing. ### Complexity Constant. ### Example ### See also | | | | --- | --- | | [at](at "cpp/utility/basic stacktrace/at") (C++23) | access specified stacktrace entry with bounds checking (public member function) | cpp std::hash(std::basic_stacktrace) std::hash(std::basic\_stacktrace) ================================= | Defined in header `[<stacktrace>](../../header/stacktrace "cpp/header/stacktrace")` | | | | --- | --- | --- | | ``` template< class Allocator > struct hash<std::basic_stacktrace<Allocator>>; ``` | | (since C++23) | The template specialization of `[std::hash](../hash "cpp/utility/hash")` for `std::basic_stacktrace` allows users to obtain hashes of values of type `std::basic_stacktrace`. `operator()` of this specialization is noexcept. ### Example ### See also | | | | --- | --- | | [hash](../hash "cpp/utility/hash") (C++11) | hash function object (class template) | | [std::hash<std::stacktrace\_entry>](../stacktrace_entry/hash "cpp/utility/stacktrace entry/hash") (C++23) | hash support for `std::stacktrace_entry` (class template specialization) | cpp std::basic_stacktrace<Allocator>::swap std::basic\_stacktrace<Allocator>::swap ======================================= | | | | | --- | --- | --- | | ``` void swap( basic_stacktrace& other ) noexcept(/* see below */); ``` | | (since C++23) | Exchanges the contents of the container with those of `other`. Does not invoke any move, copy, or swap operations on individual `stacktrace_entry` objects. All iterators and references remain valid. The past-the-end iterator is invalidated. If `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<allocator_type>::propagate\_on\_container\_swap::value` is true, then the allocators are exchanged using an unqualified call to non-member `swap`. Otherwise, they are not swapped (and if `get_allocator() != other.get_allocator()`, the behavior is undefined). ### Parameters | | | | | --- | --- | --- | | other | - | `basic_stacktrace` to exchange the contents with | ### Return value (none). ### Exceptions [`noexcept`](../../language/noexcept_spec "cpp/language/noexcept spec") specification: `noexcept([std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<Allocator>::propagate\_on\_container\_swap::value || [std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<Allocator>::is\_always\_equal::value)` ### Complexity Constant. ### Example ### See also | | | | --- | --- | | [std::swap(std::basic\_stacktrace)](swap2 "cpp/utility/basic stacktrace/swap2") (C++23) | specializes the `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | cpp std::basic_stacktrace<Allocator>::max_size std::basic\_stacktrace<Allocator>::max\_size ============================================ | | | | | --- | --- | --- | | ``` size_type max_size() const noexcept; ``` | | (since C++23) | Returns the maximum number of elements the underlying container (typically a `[std::vector](../../container/vector "cpp/container/vector")`) is able to hold due to system or library implementation limitations, i.e. `[std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(begin(), end())` for the largest underlying container. ### Parameters (none). ### Return value Maximum number of elements. ### Complexity Constant. ### Notes This value typically reflects the theoretical limit on the size of the underlying container, at most `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<difference_type>::max()`. At runtime, the size of the container may be limited to a value smaller than `max_size()` by the amount of RAM available. ### Example ``` #include <iostream> #include <stacktrace> int main() { std::stacktrace trace; std::cout << "Maximum size of a 'basic_stacktrace' is " << trace.max_size() << "\n"; } ``` Possible output: ``` Maximum size of a 'basic_stacktrace' is 1152921504606846975 ``` ### See also | | | | --- | --- | | [size](size "cpp/utility/basic stacktrace/size") (C++23) | returns the number of stacktrace entries (public member function) | cpp std::swap(std::basic_stacktrace) std::swap(std::basic\_stacktrace) ================================= | Defined in header `[<stacktrace>](../../header/stacktrace "cpp/header/stacktrace")` | | | | --- | --- | --- | | ``` template< class Allocator > void swap( std::basic_stacktrace<Allocator>& lhs, std::basic_stacktrace<Allocator>& rhs ) noexcept(noexcept(lhs.swap(rhs))); ``` | | (since C++23) | Specializes the `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` algorithm for `std::basic_stacktrace`. Swaps the contents of `lhs` and `rhs`. Equivalent to `lhs.swap(rhs);`. ### Parameters | | | | | --- | --- | --- | | lhs, rhs | - | stacktraces whose contents to swap | ### Return value (none). ### Complexity Constant. ### Example ### See also | | | | --- | --- | | [swap](swap "cpp/utility/basic stacktrace/swap") (C++23) | swaps the contents (public member function) |
programming_docs
cpp std::basic_stacktrace<Allocator>::operator= std::basic\_stacktrace<Allocator>::operator= ============================================ | | | | | --- | --- | --- | | ``` basic_stacktrace& operator=( const basic_stacktrace& other ); ``` | (1) | (since C++23) | | ``` basic_stacktrace& operator=( basic_stacktrace&& other ) noexcept(/* see below */); ``` | (2) | (since C++23) | Replaces the contents of the `basic_stacktrace`. 1) Copy assignment operator. Replaces the contents with a copy of the contents of `other`. If `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<allocator_type>::propagate\_on\_container\_copy\_assignment::value` is `true`, the allocator of `*this` is replaced by a copy of that of `other`. If the allocator of `*this` after assignment would compare unequal to its old value, the old allocator is used to deallocate the memory, then the new allocator is used to allocate it before copying the entries. Otherwise, the memory owned by `*this` may be reused when possible. 2) Move assignment operator. Replaces the contents with those of `other` using move semantics (i.e. the data in `other` is moved from `other` into `*this`). `other` is in a valid but unspecified state afterwards. If `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<allocator_type>::propagate\_on\_container\_move\_assignment::value` is `true`, the allocator of `*this` is replaced by a copy of that of `other`. If it is `false` and the allocators of `*this` and `other` do not compare equal, `*this` cannot take ownership of the memory owned by `other` and must assign each entries individually, allocating additional memory using its own allocator as needed. In any case, the stacktrace entries originally belong to `*this` may be either destroyed or replaced by element-wise assignment. `*this` may be set to empty on allocation failure if the implementation strengthens the exception specification. ### Parameters | | | | | --- | --- | --- | | other | - | another `basic_stacktrace` to use as source | ### Return value `*this`. ### Complexity 1) Linear in the size of `*this` and `other`. 2) Linear in the size of `*this` unless the allocators do not compare equal and do not propagate, in which case linear in the size of `*this` and `other`. ### Exceptions 1) May throw implementation-defined exceptions. 2) [`noexcept`](../../language/noexcept_spec "cpp/language/noexcept spec") specification: `noexcept([std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<Allocator>::propagate\_on\_container\_move\_assignment::value || [std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<Allocator>::is\_always\_equal::value)` ### Notes After container move assignment (overload (2)), unless element-wise move assignment is forced by incompatible allocators, references, pointers, and iterators (other than the end iterator) to `other` remain valid, but refer to elements that are now in `*this`. The current standard makes this guarantee via the blanket statement in [[container.requirements.general]/12](https://eel.is/c++draft/container.requirements.general#12), and a more direct guarantee is under consideration via [LWG 2321](https://cplusplus.github.io/LWG/issue2321). ### Example ### See also | | | | --- | --- | | [(constructor)](basic_stacktrace "cpp/utility/basic stacktrace/basic stacktrace") (C++23) | creates a new `basic_stacktrace` (public member function) | cpp std::basic_stacktrace<Allocator>::rend, std::basic_stacktrace<Allocator>::crend std::basic\_stacktrace<Allocator>::rend, std::basic\_stacktrace<Allocator>::crend ================================================================================= | | | | | --- | --- | --- | | ``` const_reverse_iterator rend() const noexcept; ``` | (1) | (since C++23) | | ``` const_reverse_iterator crend() const noexcept; ``` | (2) | (since C++23) | Returns a reverse iterator pointing past the last entry of the reversed `basic_stacktrace`. It corresponds to the iterator preceding the first entry of the original `basic_stacktrace`. This iterator acts as a placeholder, attempting to dereference it results in undefined behavior. ![range-rbegin-rend.svg]() ### Parameters (none). ### Return value The end iterator of the reversed `basic_stacktrace`. ### Complexity Constant. ### Example ``` #include <algorithm> #include <iostream> #include <stacktrace> int main() { auto trace = std::stacktrace::current(); auto empty_trace = std::stacktrace{}; // Print stacktrace. std::for_each(trace.rbegin(), trace.rend(), [](const auto& f) { std::cout << f << '\n'; }); if (empty_trace.rbegin() == empty_trace.rend()) std::cout << "stacktrace 'empty_trace' is indeed empty.\n"; } ``` Possible output: ``` 0x0000000000402A29 in ./prog.exe __libc_start_main in /lib/x86_64-linux-gnu/libc.so.6 0x0000000000402BA5 in ./prog.exe stacktrace 'empty_trace' is indeed empty. ``` ### See also | | | | --- | --- | | [rbegincrbegin](rbegin "cpp/utility/basic stacktrace/rbegin") (C++23) | returns a reverse iterator to the beginning (public member function) | cpp operator==, operator<=>(std::basic_stacktrace) operator==, operator<=>(std::basic\_stacktrace) =============================================== | | | | | --- | --- | --- | | ``` template< class Allocator2 > friend bool operator==( const basic_stacktrace& lhs, const basic_stacktrace<Allocator2>& rhs ) noexcept; ``` | (1) | (since C++23) | | ``` template< class Allocator2 > friend std::strong_ordering operator<=>( const basic_stacktrace& lhs, const basic_stacktrace<Allocator2>& rhs ) noexcept; ``` | (2) | (since C++23) | 1) Checks if the contents of `lhs` and `rhs` are equal, that is, they have the same number of elements and each element in `lhs` compares equal with the element in `rhs` at the same position. Equivalent to `return [std::equal](http://en.cppreference.com/w/cpp/algorithm/equal)(lhs.begin(), lhs.end(), rhs.begin(), rhs.end());`. 2) Returns the relative order of the numbers of stacktrace entries in `lhs` and `rhs` if they are not equal. Otherwise (if the numbers of elements of `lhs` and `rhs` are equal), returns the lexicographical order of the elements of `lhs` and `rhs`. Equivalent to `if (auto cmp = lhs.size() <=> rhs.size(); cmp != 0) return cmp; else return [std::lexicographical\_compare\_three\_way](http://en.cppreference.com/w/cpp/algorithm/lexicographical_compare_three_way)(lhs.begin(), lhs.end(), rhs. begin(), rhs.end());`. These function templates are not visible to ordinary [unqualified](../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../language/adl "cpp/language/adl") when `std::basic_stacktrace<Allocator>` is an associated class of the arguments. The `<`, `<=`, `>`, `>=`, and `!=` operators are [synthesized](../../language/operators#Relational_operators "cpp/language/operators") from `operator<=>` and `operator==` respectively. ### Parameters | | | | | --- | --- | --- | | lhs, rhs | - | `basic_stacktrace`s whose contents to compare | ### Return value 1) `true` if the contents of `lhs` and `rhs` are equal, `false` otherwise. 2) `lhs.size() <=> rhs.size()` if the result is not `std::strong_order::equal`, the lexicographical order of the elements of `lhs` and `rhs` otherwise. ### Complexity 1-2) Constant if `lhs` and `rhs` are of different size, linear in the size of `lhs` otherwise. ### Example cpp std::basic_stacktrace<Allocator>::empty std::basic\_stacktrace<Allocator>::empty ======================================== | | | | | --- | --- | --- | | ``` [[nodiscard]] bool empty() const noexcept; ``` | | (since C++23) | Checks if the stacktrace has no stacktrace entries. ### Parameters (none). ### Return value `true` if the stacktrace is empty, `false` otherwise. ### Complexity Constant. ### Example ``` #include <stacktrace> #include <iostream> int main() { std::cout << std::boolalpha; std::stacktrace bktr; std::cout << "Initially, bktr.empty(): " << bktr.empty() << '\n'; bktr = std::stacktrace::current(); std::cout << "After getting entries, bktr.empty(): " << bktr.empty() << '\n'; } ``` Possible output: ``` Initially, bktr.empty(): true After getting entries, bktr.empty(): false ``` ### See also | | | | --- | --- | | [size](size "cpp/utility/basic stacktrace/size") (C++23) | returns the number of stacktrace entries (public member function) | cpp std::basic_stacktrace<Allocator>::begin, std::basic_stacktrace<Allocator>::cbegin std::basic\_stacktrace<Allocator>::begin, std::basic\_stacktrace<Allocator>::cbegin =================================================================================== | | | | | --- | --- | --- | | ``` const_iterator begin() const noexcept; ``` | (1) | (since C++23) | | ``` const_iterator cbegin() const noexcept; ``` | (2) | (since C++23) | Returns an iterator to the first entry of the `basic_stacktrace`. If the `basic_stacktrace` is empty, the returned iterator is equal to `end()`. ![range-begin-end.svg]() ### Parameters (none). ### Return value Iterator to the first entry. ### Complexity Constant. ### Example ``` #include <algorithm> #include <iostream> #include <stacktrace> int main() { auto trace = std::stacktrace::current(); auto empty_trace = std::stacktrace{}; // Print stacktrace. std::for_each(trace.begin(), trace.end(), [](const auto& f) { std::cout << f << '\n'; }); if (empty_trace.begin() == empty_trace.end()) std::cout << "stacktrace 'empty_trace' is indeed empty.\n"; } ``` Possible output: ``` 0x0000000000402BA8 in ./prog.exe __libc_start_main in /lib/x86_64-linux-gnu/libc.so.6 0x0000000000402A29 in ./prog.exe stacktrace 'empty_trace' is indeed empty. ``` ### See also | | | | --- | --- | | [endcend](end "cpp/utility/basic stacktrace/end") (C++23) | returns an iterator to the end (public member function) | cpp std::basic_stacktrace<Allocator>::end, std::basic_stacktrace<Allocator>::cend std::basic\_stacktrace<Allocator>::end, std::basic\_stacktrace<Allocator>::cend =============================================================================== | | | | | --- | --- | --- | | ``` const_iterator end() const noexcept; ``` | (1) | (since C++23) | | ``` const_iterator cend() const noexcept; ``` | (2) | (since C++23) | Returns the iterator pointing past the last entry of the `basic_stacktrace`. This iterator acts as a placeholder; attempting to dereference it results in undefined behavior. ![range-begin-end.svg]() ### Parameters (none). ### Return value The end iterator. ### Complexity Constant. ### Example ``` #include <algorithm> #include <iostream> #include <stacktrace> int main() { auto trace = std::stacktrace::current(); auto empty_trace = std::stacktrace{}; // Print stacktrace. std::for_each(trace.begin(), trace.end(), [](const auto& f) { std::cout << f << '\n'; }); if (empty_trace.begin() == empty_trace.end()) std::cout << "stacktrace 'empty_trace' is indeed empty.\n"; } ``` Possible output: ``` 0x0000000000402BA8 in ./prog.exe __libc_start_main in /lib/x86_64-linux-gnu/libc.so.6 0x0000000000402A29 in ./prog.exe stacktrace 'empty_trace' is indeed empty. ``` ### See also | | | | --- | --- | | [begincbegin](begin "cpp/utility/basic stacktrace/begin") (C++23) | returns an iterator to the beginning (public member function) | cpp std::source_location::function_name std::source\_location::function\_name ===================================== | | | | | --- | --- | --- | | ``` constexpr const char* function_name() const noexcept; ``` | | (since C++20) | Returns the name of the function associated with the position represented by this object, if any. ### Parameters (none). ### Return value If this object represents a position in a body of a function, returns an implementation-defined null-terminated byte string corresponding to the name of the function. Otherwise, an empty string is returned. ### Example `std::source_location::function_name` may help to obtain the names of functions (including the special functions) alongside with their signatures. ``` #include <cstdio> #include <utility> #include <source_location> inline void print_function_name( const std::source_location& location = std::source_location::current()) { std::puts(location.function_name()); // prints the name of the caller } void foo(double &&) { print_function_name(); } namespace bar { void baz() { print_function_name(); } } template <typename T> auto pub(T) { print_function_name(); return 42; } struct S { S() { print_function_name(); } S(int) { print_function_name(); } ~S() { print_function_name(); } S& operator=(S const&) { print_function_name(); return *this; } S& operator=(S&&) { print_function_name(); return *this; } }; int main(int, char const* const[]) { print_function_name(); foo(3.14); bar::baz(); pub(0xFULL); S p; S q{42}; p = q; p = std::move(q); [] { print_function_name(); }(); } ``` Possible output: ``` int main(int, const char* const*) void foo(double&&) void bar::baz() auto pub(T) [with T = long long unsigned int] S::S() S::S(int) S& S::operator=(const S&) S& S::operator=(S&&) main(int, const char* const*)::<lambda()> S::~S() S::~S() ``` ### See also | | | | --- | --- | | [line](line "cpp/utility/source location/line") | return the line number represented by this object (public member function) | | [column](column "cpp/utility/source location/column") | return the column number represented by this object (public member function) | | [file\_name](file_name "cpp/utility/source location/file name") | return the file name represented by this object (public member function) | cpp std::source_location::source_location std::source\_location::source\_location ======================================= | | | | | --- | --- | --- | | ``` constexpr source_location() noexcept; ``` | (1) | (since C++20) | | ``` source_location( const source_location& other ); ``` | (2) | (since C++20) | | ``` source_location( source_location&& other ) noexcept; ``` | (3) | (since C++20) | 1) Constructs a `source_location` object of unspecified value. 2-3) Copy and move constructors. It is unspecified whether they are trivial and/or constexpr. ### Parameters | | | | | --- | --- | --- | | other | - | another `source_location` to copy or move from | ### Example ``` #include <iomanip> #include <iostream> #include <ranges> #include <vector> #include <source_location> #include <string_view> // GCC specific type name printer #if (__GNUG__ >= 11) template <typename T> auto type_name_helper(const std::source_location s = std::source_location::current()) { using std::operator""sv; const std::string_view fun_name{s.function_name()}; constexpr auto prefix {"[with T = "sv}; const auto type_name_begin {fun_name.find(prefix)}; if (""sv.npos == type_name_begin) return ""sv; const std::size_t first {type_name_begin + prefix.length()}; return std::string_view{fun_name.cbegin() + first, fun_name.cend() - 1}; } template <typename T> auto type_name() { return type_name_helper<T>(); } #endif void print(std::string_view const comment, std::source_location const l) { std::cout << comment << ":\n" << " file_name : " << std::quoted(l.file_name()) << '\n' << " function_name : " << std::quoted(l.function_name()) << '\n' << " line : " << l.line() << '\n' << " column : " << l.column() << '\n'; } int main() { constexpr std::source_location default_constructed; print("default constructed", default_constructed); constexpr std::source_location current = std::source_location::current(); print("current", current); # if (__GNUG__ >= 11) const std::vector<std::vector<int>> v{ {1,2}, {3,4,5}, {6} }; auto jv = std::ranges::join_view(v); std::cout << '\n' << '[' << type_name<int>() << "]\n" << '[' << type_name<double*>() << "]\n" << '[' << type_name<decltype([](){})>() << "]\n" << '[' << type_name<decltype(type_name<int>())>() << "]\n" << '[' << type_name<decltype(jv)>() << "]\n" ; # endif } ``` Possible output: ``` default constructed: file_name : "" function_name : "" line : 0 column : 0 current: file_name : "main.cpp" function_name : "int main()" line : 39 column : 75 [int] [double*] [main()::<lambda()>] [std::basic_string_view<char>] [std::ranges::join_view<std::ranges::ref_view<const std::vector<std::vector<int> > > >] ``` ### See also | | | | --- | --- | | [current](current "cpp/utility/source location/current") [static] | constructs a new `source_location` corresponding to the location of the call site (public static member function) | | [(constructor)](../stacktrace_entry/stacktrace_entry "cpp/utility/stacktrace entry/stacktrace entry") (C++23) | constructs a new `stacktrace_entry` (public member function of `std::stacktrace_entry`) | cpp std::source_location::current std::source\_location::current ============================== | | | | | --- | --- | --- | | ``` static consteval source_location current() noexcept; ``` | | (since C++20) | Constructs a new `source_location` object corresponding to the location of the call site. ### Parameters (none). ### Return value If `current()` is invoked directly (via a function call that names `current()`), it returns a `source_location` object with implementation-defined values representing the location of the call. The values should be affected by the [`#line` preprocessor directive](../../preprocessor/line "cpp/preprocessor/line") in the same manner as the predefined macros `__LINE__` and `__FILE__`. If `current()` is used in a [default member initializer](../../language/data_members#Member_initialization "cpp/language/data members"), the return value corresponds to the location of the constructor definition or [aggregate initialization](../../language/aggregate_initialization "cpp/language/aggregate initialization") that initializes the data member. If `current()` is used in a default argument, the return value corresponds to the location of the call to `current()` at the call site. If `current()` is invoked in any other manner, the return value is unspecified. ### Notes `std::source_location::current` typically requires compiler's built-in implementation. ### Example ``` #include <source_location> #include <iostream> struct src_rec { std::source_location srcl = std::source_location::current(); int dummy = 0; src_rec(std::source_location loc = std::source_location::current()) : srcl(loc) // values of member refer to the location of the calling function {} src_rec(int i) : // values of member refer to this location dummy(i) {} src_rec(double) // values of member refer to this location {} }; std::source_location src_clone(std::source_location a = std::source_location::current()) { return a; } std::source_location src_make() { std::source_location b = std::source_location::current(); return b; } int main() { src_rec srec0; src_rec srec1(0); src_rec srec2(0.0); auto s0 = std::source_location::current(); auto s1 = src_clone(s0); auto s2 = src_clone(); auto s3 = src_make(); std::cout << srec0.srcl.line() << ' ' << srec0.srcl.function_name() << '\n' << srec1.srcl.line() << ' ' << srec1.srcl.function_name() << '\n' << srec2.srcl.line() << ' ' << srec2.srcl.function_name() << '\n' << s0.line() << ' ' << s0.function_name() << '\n' << s1.line() << ' ' << s1.function_name() << '\n' << s2.line() << ' ' << s2.function_name() << '\n' << s3.line() << ' ' << s3.function_name() << '\n'; } ``` Possible output: ``` 31 int main() 12 src_rec::src_rec(int) 15 src_rec::src_rec(double) 34 int main() 34 int main() 36 int main() 25 std::source_location src_make() ``` ### See also | | | | --- | --- | | [(constructor)](source_location "cpp/utility/source location/source location") | constructs a new `source_location` with implementation-defined values (public member function) | | [current](../basic_stacktrace/current "cpp/utility/basic stacktrace/current") [static] (C++23) | obtains the current stacktrace or its given part (public static member function of `std::basic_stacktrace<Allocator>`) |
programming_docs
cpp std::source_location::file_name std::source\_location::file\_name ================================= | | | | | --- | --- | --- | | ``` constexpr const char* file_name() const noexcept; ``` | | (since C++20) | Returns the name of the current source file represented by this object, represented as a null-terminated byte string. ### Parameters (none). ### Return value The name of the current source file represented by this object, represented as a null-terminated byte string. ### Example ``` #include <iostream> #include <source_location> void print_this_file_name( std::source_location location = std::source_location::current()) { // Name of file that contains the call site of this function. std::cout << "File: " << location.file_name() << '\n'; } int main() { #line 1 "cppreference.cpp" print_this_file_name(); } ``` Output: ``` File: cppreference.cpp ``` ### See also | | | | --- | --- | | [line](line "cpp/utility/source location/line") | return the line number represented by this object (public member function) | | [column](column "cpp/utility/source location/column") | return the column number represented by this object (public member function) | | [function\_name](function_name "cpp/utility/source location/function name") | return the name of the function represented by this object, if any (public member function) | | [source\_file](../stacktrace_entry/source_file "cpp/utility/stacktrace entry/source file") (C++23) | gets the name of the source file that lexically contains the expression or statement whose evaluation is represented by the `stacktrace_entry` (public member function of `std::stacktrace_entry`) | | [Filename and line information](../../preprocessor/line "cpp/preprocessor/line") | cpp std::source_location::column std::source\_location::column ============================= | | | | | --- | --- | --- | | ``` constexpr std::uint_least32_t column() const noexcept; ``` | | (since C++20) | Returns an implementation-defined value representing some offset from the start of the line represented by this object (i.e., the column number). Column numbers are presumed to be 1-indexed. ### Parameters (none). ### Return value An implementation-defined value representing some offset from the start of the line represented by this object (i.e., the column number). An implementation is encouraged to use `0` when the column number is unknown. ### Example ``` #include <iostream> #include <source_location> template<typename T = std::source_location> inline void pos(const T& location = T::current()) { std::cout << "(" << location.line() << ':' << location.column() << ") "; } int main() { // ↓: column #9 pos(); std::cout << "Proxima\n"; // row #18 pos(); std::cout << "Centauri\n"; // row #19 // ↑: column #11 } ``` Possible output: ``` (18:9) Proxima (19:11) Centauri ``` ### See also | | | | --- | --- | | [line](line "cpp/utility/source location/line") | return the line number represented by this object (public member function) | | [file\_name](file_name "cpp/utility/source location/file name") | return the file name represented by this object (public member function) | | [function\_name](function_name "cpp/utility/source location/function name") | return the name of the function represented by this object, if any (public member function) | | [Filename and line information](../../preprocessor/line "cpp/preprocessor/line") | cpp std::source_location::line std::source\_location::line =========================== | | | | | --- | --- | --- | | ``` constexpr std::uint_least32_t line() const noexcept; ``` | | (since C++20) | Returns the line number represented by this object. ### Parameters (none). ### Return value The line number represented by this object. An implementation is encouraged to return `0` when the line number is unknown. ### Example ``` #include <iostream> #include <string_view> #include <source_location> inline void cur_line( const std::string_view message = "", const std::source_location& location = std::source_location::current()) { std::cout << location.line() // <- the line # of a call site << ") " << message; } int main() { cur_line("++\n"); cur_line(); std::cout << "Hello,\n"; cur_line(); std::cout << "C++20!\n"; cur_line("--\n"); } ``` Output: ``` 17) ++ 18) Hello, 19) C++20! 20) -- ``` ### See also | | | | --- | --- | | [column](column "cpp/utility/source location/column") | return the column number represented by this object (public member function) | | [file\_name](file_name "cpp/utility/source location/file name") | return the file name represented by this object (public member function) | | [function\_name](function_name "cpp/utility/source location/function name") | return the name of the function represented by this object, if any (public member function) | | [source\_line](../stacktrace_entry/source_line "cpp/utility/stacktrace entry/source line") (C++23) | gets the line number that lexically relates the evaluation represented by the `stacktrace_entry` (public member function of `std::stacktrace_entry`) | | [Filename and line information](../../preprocessor/line "cpp/preprocessor/line") | cpp std::pointer_to_unary_function std::pointer\_to\_unary\_function ================================= | | | | | --- | --- | --- | | ``` template< class Arg, class Result > class pointer_to_unary_function : public std::unary_function<Arg, Result>; ``` | | (deprecated in C++11) (removed in C++17) | `std::pointer_to_unary_function` is a function object that acts as a wrapper around a unary function. ### Member functions | | | | --- | --- | | (constructor) | constructs a new `pointer_to_unary_function` object with the supplied function (public member function) | | operator() | calls the stored function (public member function) | std::pointer\_to\_unary\_function::pointer\_to\_unary\_function ---------------------------------------------------------------- | | | | | --- | --- | --- | | ``` explicit pointer_to_unary_function( Result (*f)(Arg) ); ``` | | | Constructs a `pointer_to_unary_function` function object with the stored function `f`. ### Parameters | | | | | --- | --- | --- | | f | - | pointer to a function to store | std::pointer\_to\_unary\_function::operator() ---------------------------------------------- | | | | | --- | --- | --- | | ``` Result operator()( Arg x ) const; ``` | | | Calls the stored function. ### Parameters | | | | | --- | --- | --- | | x | - | argument to pass to the function | ### Return value The value returned by the called function. ### See also | | | | --- | --- | | [pointer\_to\_binary\_function](pointer_to_binary_function "cpp/utility/functional/pointer to binary function") (deprecated in C++11)(removed in C++17) | adaptor-compatible wrapper for a pointer to binary function (class template) | | [ptr\_fun](ptr_fun "cpp/utility/functional/ptr fun") (deprecated in C++11)(removed in C++17) | creates an adaptor-compatible function object wrapper from a pointer to function (function template) | cpp std::mem_fun std::mem\_fun ============= | Defined in header `[<functional>](../../header/functional "cpp/header/functional")` | | | | --- | --- | --- | | ``` template< class Res, class T > std::mem_fun_t<Res,T> mem_fun( Res (T::*f)() ); ``` | (1) | (deprecated in C++11) (removed in C++17) | | ``` template< class Res, class T > std::const_mem_fun_t<Res,T> mem_fun( Res (T::*f)() const ); ``` | (1) | (deprecated in C++11) (removed in C++17) | | ``` template< class Res, class T, class Arg > std::mem_fun1_t<Res,T,Arg> mem_fun( Res (T::*f)(Arg) ); ``` | (2) | (deprecated in C++11) (removed in C++17) | | ``` template< class Res, class T, class Arg > std::const_mem_fun1_t<Res,T,Arg> mem_fun( Res (T::*f)(Arg) const ); ``` | (2) | (deprecated in C++11) (removed in C++17) | Creates a member function wrapper object, deducing the target type from the template arguments. The wrapper object expects a pointer to an object of type `T` as the first parameter to its `operator()`. 1) Effectively calls `[std::mem\_fun\_t](http://en.cppreference.com/w/cpp/utility/functional/mem_fun_t)<Res,T>(f)` or `[std::const\_mem\_fun\_t](http://en.cppreference.com/w/cpp/utility/functional/mem_fun_t)<Res,T>(f)`. 2) Effectively calls `[std::mem\_fun1\_t](http://en.cppreference.com/w/cpp/utility/functional/mem_fun_t)<Res,T,Arg>(f)` or `[std::const\_mem\_fun1\_t](http://en.cppreference.com/w/cpp/utility/functional/mem_fun_t)<Res,T,Arg>(f)`. This function and the related types were deprecated in C++11 and removed in C++17 in favor of the more general `[std::mem\_fn](mem_fn "cpp/utility/functional/mem fn")` and `[std::bind](bind "cpp/utility/functional/bind")`, both of which create callable adaptor-compatible function objects from member functions. ### Parameters | | | | | --- | --- | --- | | f | - | pointer to a member function to create a wrapper for | ### Return value A function object wrapping `f`. ### Exceptions May throw implementation-defined exceptions. ### Notes The difference between `std::mem_fun` and `[std::mem\_fun\_ref](http://en.cppreference.com/w/cpp/utility/functional/mem_fun_ref)` is that the former produces an function wrapper that expects a pointer to an object, whereas the latter -- a reference. ### Example demonstrates `std::mem_fun` usage and compares it with `[std::mem\_fn](mem_fn "cpp/utility/functional/mem fn")`. C++11/14 compatible compilation mode might be necessary (e.g. g++/clang++ with -std=c++11, cl with /std:c++11). ``` #include <iostream> #include <functional> struct S { int get_data() const { return data; } void no_args() const { std::cout << "void S::no_args() const\n"; } void one_arg(int) { std::cout << "void S::one_arg()\n"; } void two_args(int, int) { std::cout << "void S::two_args(int, int)\n"; } int data{42}; }; int main() { S s; auto p = std::mem_fun(&S::get_data); std::cout << "s.get_data(): " << p(&s) << '\n'; auto p0 = std::mem_fun(&S::no_args); p0(&s); auto p1 = std::mem_fun(&S::one_arg); p1(&s, 1); // auto p2 = std::mem_fun(&S::two_args); // Error: mem_fun supports only member functions // without parameters or with only one parameter. // Thus, std::mem_fn is a better alternative: auto p2 = std::mem_fn(&S::two_args); p2(s, 1, 2); // auto pd = std::mem_fun(&S::data); // Error: pointers to data members are not supported. // Use std::mem_fn instead: auto pd = std::mem_fn(&S::data); std::cout << "s.data = " << pd(s) << '\n'; } ``` Possible output: ``` s.get_data(): 42 void S::no_args() const void S::one_arg(int) void S::two_args(int, int) s.data = 42 ``` ### See also | | | | --- | --- | | [mem\_fn](mem_fn "cpp/utility/functional/mem fn") (C++11) | creates a function object out of a pointer to a member (function template) | | [mem\_fun\_ref](mem_fun_ref "cpp/utility/functional/mem fun ref") (deprecated in C++11)(removed in C++17) | creates a wrapper from a pointer to member function, callable with a reference to object (function template) | cpp std::bad_function_call std::bad\_function\_call ======================== | Defined in header `[<functional>](../../header/functional "cpp/header/functional")` | | | | --- | --- | --- | | ``` class bad_function_call; ``` | | (since C++11) | `std::bad_function_call` is the type of the exception thrown by [`std::function::operator()`](function/operator() "cpp/utility/functional/function/operator()") if the function wrapper has no target. ![std-bad function call-inheritance.svg]() Inheritance diagram. ### Member functions | | | | --- | --- | | (constructor) | constructs a new `bad_function_call` object (public member function) | | operator= | replaces the `bad_function_call` object (public member function) | | what | returns the explanatory string (public member function) | std::bad\_function\_call::bad\_function\_call ---------------------------------------------- | | | | | --- | --- | --- | | ``` bad_function_call() noexcept; ``` | (1) | (since C++11) | | ``` bad_function_call( const bad_function_call& other ) noexcept; ``` | (2) | (since C++11) | Constructs a new `bad_function_call` object with an implementation-defined null-terminated byte string which is accessible through [`what()`](../../error/exception/what "cpp/error/exception/what"). 1) Default constructor. 2) Copy constructor. If `*this` and `other` both have dynamic type `std::bad_function_call` then `[std::strcmp](http://en.cppreference.com/w/cpp/string/byte/strcmp)(what(), other.what()) == 0`. ### Parameters | | | | | --- | --- | --- | | other | - | another exception object to copy | std::bad\_function\_call::operator= ------------------------------------ | | | | | --- | --- | --- | | ``` bad_function_call& operator=( const bad_function_call& other ) noexcept; ``` | | (since C++11) | Assigns the contents with those of `other`. If `*this` and `other` both have dynamic type `std::bad_function_call` then `[std::strcmp](http://en.cppreference.com/w/cpp/string/byte/strcmp)(what(), other.what()) == 0` after assignment. ### Parameters | | | | | --- | --- | --- | | other | - | another exception object to assign with | ### Return value `*this`. std::bad\_function\_call::what ------------------------------- | | | | | --- | --- | --- | | ``` virtual const char* what() const noexcept; ``` | | (since C++11) | Returns the explanatory string. ### Parameters (none). ### Return value Pointer to a null-terminated string with explanatory information. The string is suitable for conversion and display as a `[std::wstring](../../string/basic_string "cpp/string/basic string")`. The pointer is guaranteed to be valid at least until the exception object from which it is obtained is destroyed, or until a non-const member function (e.g. copy assignment operator) on the exception object is called. ### Notes Implementations are allowed but not required to override `what()`. Inherited from [std::exception](../../error/exception "cpp/error/exception") ------------------------------------------------------------------------------ ### Member functions | | | | --- | --- | | [(destructor)](../../error/exception/~exception "cpp/error/exception/~exception") [virtual] | destroys the exception object (virtual public member function of `std::exception`) | | [what](../../error/exception/what "cpp/error/exception/what") [virtual] | returns an explanatory string (virtual public member function of `std::exception`) | ### Example ``` #include <iostream> #include <functional> int main() { std::function<int()> f = nullptr; try { f(); } catch(const std::bad_function_call& e) { std::cout << e.what() << '\n'; } } ``` Possible output: ``` bad function call ``` ### See also | | | | --- | --- | | [function](function "cpp/utility/functional/function") (C++11) | wraps callable object of any copy constructible type with specified function call signature (class template) | cpp std::bind1st, std::bind2nd std::bind1st, std::bind2nd ========================== | Defined in header `[<functional>](../../header/functional "cpp/header/functional")` | | | | --- | --- | --- | | ``` template< class F, class T > std::binder1st<F> bind1st( const F& f, const T& x ); ``` | (1) | (deprecated in C++11) (removed in C++17) | | ``` template< class F, class T > std::binder2nd<F> bind2nd( const F& f, const T& x ); ``` | (2) | (deprecated in C++11) (removed in C++17) | Binds a given argument `x` to a first or second parameter of the given binary function object `f`. That is, stores `x` within the resulting wrapper, which, if called, passes `x` as the first or the second parameter of `f`. 1) Binds the first argument of `f` to `x`. Effectively calls `[std::binder1st](http://en.cppreference.com/w/cpp/utility/functional/binder12)<F>(f, typename F::first\_argument\_type(x))`. 2) Binds the second argument of `f` to `x`. Effectively calls `[std::binder2nd](http://en.cppreference.com/w/cpp/utility/functional/binder12)<F>(f, typename F::second\_argument\_type(x))`. ### Parameters | | | | | --- | --- | --- | | f | - | pointer to a function to bind an argument to | | x | - | argument to bind to `f` | ### Return value A function object wrapping `f` and `x`. ### Exceptions May throw implementation-defined exceptions. ### Example ``` #include <iostream> #include <iomanip> #include <algorithm> #include <functional> #include <cmath> #include <cstddef> #include <vector> int main() { std::vector<double> a = {0, 30, 45, 60, 90, 180}; std::vector<double> r(a.size()); const double pi = std::acos(-1); // since C++20 use std::numbers::pi std::transform(a.begin(), a.end(), r.begin(), std::bind1st(std::multiplies<double>(), pi / 180.)); // an equivalent lambda is: [pi](double a){ return a*pi / 180.; }); for(std::size_t n = 0; n < a.size(); ++n) std::cout << std::setw(3) << a[n] << "° = " << std::fixed << r[n] << " rad\n" << std::defaultfloat; } ``` Output: ``` 0° = 0.000000 rad 30° = 0.523599 rad 45° = 0.785398 rad 60° = 1.047198 rad 90° = 1.570796 rad 180° = 3.141593 rad ``` ### See also | | | | --- | --- | | [binder1stbinder2nd](binder12 "cpp/utility/functional/binder12") (deprecated in C++11)(removed in C++17) | function object holding a binary function and one of its arguments (class template) | | [bind\_frontbind\_back](bind_front "cpp/utility/functional/bind front") (C++20)(C++23) | bind a variable number of arguments, in order, to a function object (function template) | cpp std::reference_wrapper std::reference\_wrapper ======================= | Defined in header `[<functional>](../../header/functional "cpp/header/functional")` | | | | --- | --- | --- | | ``` template< class T > class reference_wrapper; ``` | | (since C++11) | `std::reference_wrapper` is a class template that wraps a reference in a copyable, assignable object. It is frequently used as a mechanism to store references inside standard containers (like `[std::vector](../../container/vector "cpp/container/vector")`) which cannot normally hold references. Specifically, `std::reference_wrapper` is a [CopyConstructible](../../named_req/copyconstructible "cpp/named req/CopyConstructible") and [CopyAssignable](../../named_req/copyassignable "cpp/named req/CopyAssignable") wrapper around a reference to object or reference to function of type `T`. Instances of `std::reference_wrapper` are objects (they can be copied or stored in containers) but they are implicitly convertible to `T&`, so that they can be used as arguments with the functions that take the underlying type by reference. If the stored reference is [Callable](../../named_req/callable "cpp/named req/Callable"), `std::reference_wrapper` is callable with the same arguments. Helper functions `[std::ref](ref "cpp/utility/functional/ref")` and `[std::cref](ref "cpp/utility/functional/ref")` are often used to generate `std::reference_wrapper` objects. `std::reference_wrapper` is also used to pass objects by reference to `[std::bind](bind "cpp/utility/functional/bind")`, the constructor of `[std::thread](../../thread/thread "cpp/thread/thread")`, or the helper functions `[std::make\_pair](../pair/make_pair "cpp/utility/pair/make pair")` and `[std::make\_tuple](../tuple/make_tuple "cpp/utility/tuple/make tuple")`. | | | | --- | --- | | `std::reference_wrapper` is guaranteed to be [TriviallyCopyable](../../named_req/triviallycopyable "cpp/named req/TriviallyCopyable"). | (since C++17) | | | | | --- | --- | | `T` may be an incomplete type. | (since C++20) | ### Member types | type | definition | | --- | --- | | `type` | `T` | | `result_type`(deprecated in C++17)(removed in C++20) | The return type of `T` if `T` is a function. Otherwise, not defined | | `argument_type`(deprecated in C++17)(removed in C++20) | 1) if `T` is a function or pointer to function that takes one argument of type `A1`, then `argument_type` is `A1`. 2) if `T` is a pointer to member function of class `T0` that takes no arguments, then `argument_type` is `T0*`, possibly cv-qualified 3) if `T` is a class type with a member type `T::argument_type`, then `argument_type` is an alias of that. | | `first_argument_type`(deprecated in C++17)(removed in C++20) | 1) if `T` is a function or pointer to function that takes two arguments of types `A1` and `A2`, then `first_argument_type` is `A1`. 2) if `T` is a pointer to member function of class `T0` that takes one argument, then `first_argument_type` is `T0*`, possibly cv-qualified 3) if `T` is a class type with a member type `T::first_argument_type`, then `first_argument_type` is an alias of that. | | `second_argument_type`(deprecated in C++17)(removed in C++20) | 1) if `T` is a function or pointer to function that takes two arguments of type s `A1` and `A2`, then `second_argument_type` is `A2`. 2) if `T` is a pointer to member function of class `T0` that takes one argument `A1`, then `second_argument_type` is `A1`, possibly cv-qualified 3) if `T` is a class type with a member type `T::second_argument_type`, then `second_argument_type` is an alias of that. | ### Member functions | | | | --- | --- | | [(constructor)](reference_wrapper/reference_wrapper "cpp/utility/functional/reference wrapper/reference wrapper") | stores a reference in a new `std::reference_wrapper` object (public member function) | | [operator=](reference_wrapper/operator= "cpp/utility/functional/reference wrapper/operator=") | rebinds a `std::reference_wrapper` (public member function) | | [getoperator T&](reference_wrapper/get "cpp/utility/functional/reference wrapper/get") | accesses the stored reference (public member function) | | [operator()](reference_wrapper/operator() "cpp/utility/functional/reference wrapper/operator()") | calls the stored function (public member function) | ### [Deduction guides](reference_wrapper/deduction_guides "cpp/utility/functional/reference wrapper/deduction guides")(since C++17) ### Possible implementation | | | --- | | ``` namespace detail { template <class T> constexpr T& FUN(T& t) noexcept { return t; } template <class T> void FUN(T&&) = delete; } template <class T> class reference_wrapper { public: // types typedef T type; // construct/copy/destroy template <class U, class = decltype( detail::FUN<T>(std::declval<U>()), std::enable_if_t<!std::is_same_v<reference_wrapper, std::remove_cvref_t<U>>>() )> constexpr reference_wrapper(U&& u) noexcept(noexcept(detail::FUN<T>(std::forward<U>(u)))) : _ptr(std::addressof(detail::FUN<T>(std::forward<U>(u)))) {} reference_wrapper(const reference_wrapper&) noexcept = default; // assignment reference_wrapper& operator=(const reference_wrapper& x) noexcept = default; // access constexpr operator T& () const noexcept { return *_ptr; } constexpr T& get() const noexcept { return *_ptr; } template< class... ArgTypes > constexpr std::invoke_result_t<T&, ArgTypes...> operator() ( ArgTypes&&... args ) const { return std::invoke(get(), std::forward<ArgTypes>(args)...); } private: T* _ptr; }; // deduction guides template<class T> reference_wrapper(T&) -> reference_wrapper<T>; ``` | ### Example Demonstrates the use of `std::reference_wrapper` as a container of references, which makes it possible to access the same container using multiple indexes. ``` #include <algorithm> #include <list> #include <vector> #include <iostream> #include <numeric> #include <random> #include <functional> void print(auto const rem, std::ranges::range auto const& v) { for (std::cout << rem; auto const& e : v) std::cout << e << ' '; std::cout << '\n'; } int main() { std::list<int> l(10); std::iota(l.begin(), l.end(), -4); // can't use shuffle on a list (requires random access), but can use it on a vector std::vector<std::reference_wrapper<int>> v(l.begin(), l.end()); std::ranges::shuffle(v, std::mt19937{std::random_device{}()}); print("Contents of the list: ", l); print("Contents of the list, as seen through a shuffled vector: ", v); std::cout << "Doubling the values in the initial list...\n"; std::ranges::for_each(l, [](int& i) { i *= 2; }); print("Contents of the list, as seen through a shuffled vector: ", v); } ``` Possible output: ``` Contents of the list: -4 -3 -2 -1 0 1 2 3 4 5 Contents of the list, as seen through a shuffled vector: -1 2 -2 1 5 0 3 -3 -4 4 Doubling the values in the initial list... Contents of the list, as seen through a shuffled vector: -2 4 -4 2 10 0 6 -6 -8 8 ``` ### See also | | | | --- | --- | | [refcref](ref "cpp/utility/functional/ref") (C++11)(C++11) | creates a `std::reference_wrapper` with a type deduced from its argument (function template) | | [bind](bind "cpp/utility/functional/bind") (C++11) | binds one or more arguments to a function object (function template) | | [unwrap\_referenceunwrap\_ref\_decay](unwrap_reference "cpp/utility/functional/unwrap reference") (C++20)(C++20) | get the reference type wrapped in `std::reference_wrapper` (class template) |
programming_docs
cpp std::binder1st, std::binder2nd std::binder1st, std::binder2nd ============================== | Defined in header `[<functional>](../../header/functional "cpp/header/functional")` | | | | --- | --- | --- | | ``` template< class Fn > class binder1st : public std::unary_function<typename Fn::second_argument_type, typename Fn::result_type> { protected: Fn op; typename Fn::first_argument_type value; public: binder1st(const Fn& fn, const typename Fn::first_argument_type& value); typename Fn::result_type operator()(const typename Fn::second_argument_type& x) const; typename Fn::result_type operator()(typename Fn::second_argument_type& x) const; }; ``` | (1) | (deprecated in C++11) (removed in C++17) | | ``` template< class Fn > class binder2nd : public std::unary_function<typename Fn::first_argument_type, typename Fn::result_type> { protected: Fn op; typename Fn::second_argument_type value; public: binder2nd(const Fn& fn, const typename Fn::second_argument_type& value); typename Fn::result_type operator()(const typename Fn::first_argument_type& x) const; typename Fn::result_type operator()(typename Fn::first_argument_type& x) const; }; ``` | (2) | (deprecated in C++11) (removed in C++17) | A function object that binds an argument to a binary function. The value of the parameter is passed to the object at the construction time and stored within the object. Whenever the function object is invoked though `operator()`, the stored value is passed as one of the arguments, the other argument is passed as an argument of `operator()`. The resulting function object is an unary function. 1) Binds the first parameter to the value `value` given at the construction of the object. 2) Binds the second parameter to the value `value` given at the construction of the object. ### Example ``` #include <iostream> #include <functional> #include <cmath> #include <vector> const double pi = std::acos(-1); // use std::numbers::pi in C++20 int main() { // deprecated in C++11, removed in C++17 auto f1 = std::bind1st(std::multiplies<double>(), pi / 180.); // C++11 replacement auto f2 = [](double a){ return a * pi / 180.; }; for (double n : {0, 30, 45, 60, 90, 180}) std::cout << n << "°\t" << std::fixed << "= " << f1(n) << " rad (using binder)\t= " << f2(n) << " rad (using lambda)\n" << std::defaultfloat; } ``` Output: ``` 0° = 0.000000 rad (using binder) = 0.000000 rad (using lambda) 30° = 0.523599 rad (using binder) = 0.523599 rad (using lambda) 45° = 0.785398 rad (using binder) = 0.785398 rad (using lambda) 60° = 1.047198 rad (using binder) = 1.047198 rad (using lambda) 90° = 1.570796 rad (using binder) = 1.570796 rad (using lambda) 180° = 3.141593 rad (using binder) = 3.141593 rad (using lambda) ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 109](https://cplusplus.github.io/LWG/issue109) | C++98 | `operator()` could not modify to argument passed to it | added overloads to handle this | ### See also | | | | --- | --- | | [bind1stbind2nd](bind12 "cpp/utility/functional/bind12") (deprecated in C++11)(removed in C++17) | binds one argument to a binary function (function template) | cpp std::ref, std::cref std::ref, std::cref =================== | Defined in header `[<functional>](../../header/functional "cpp/header/functional")` | | | | --- | --- | --- | | | (1) | | | ``` template< class T > std::reference_wrapper<T> ref( T& t ) noexcept; ``` | (since C++11) (until C++20) | | ``` template< class T > constexpr std::reference_wrapper<T> ref( T& t ) noexcept; ``` | (since C++20) | | | (2) | | | ``` template< class T > std::reference_wrapper<T> ref( std::reference_wrapper<T> t ) noexcept; ``` | (since C++11) (until C++20) | | ``` template< class T > constexpr std::reference_wrapper<T> ref( std::reference_wrapper<T> t ) noexcept; ``` | (since C++20) | | ``` template< class T > void ref( const T&& ) = delete; ``` | (3) | (since C++11) | | | (4) | | | ``` template< class T > std::reference_wrapper<const T> cref( const T& t ) noexcept; ``` | (since C++11) (until C++20) | | ``` template< class T > constexpr std::reference_wrapper<const T> cref( const T& t ) noexcept; ``` | (since C++20) | | | (5) | | | ``` template< class T > std::reference_wrapper<const T> cref( std::reference_wrapper<T> t ) noexcept; ``` | (since C++11) (until C++20) | | ``` template< class T > constexpr std::reference_wrapper<const T> cref( std::reference_wrapper<T> t ) noexcept; ``` | (since C++20) | | ``` template< class T > void cref( const T&& ) = delete; ``` | (6) | (since C++11) | Function templates `ref` and `cref` are helper functions that generate an object of type `[std::reference\_wrapper](reference_wrapper "cpp/utility/functional/reference wrapper")`, using [template argument deduction](../../language/template_argument_deduction "cpp/language/template argument deduction") to determine the template argument of the result. | | | | --- | --- | | `T` may be an incomplete type. | (since C++20) | ### Parameters | | | | | --- | --- | --- | | t | - | lvalue reference to object that needs to be wrapped or an instance of `[std::reference\_wrapper](reference_wrapper "cpp/utility/functional/reference wrapper")` | ### Return value 1) `[std::reference\_wrapper](http://en.cppreference.com/w/cpp/utility/functional/reference_wrapper)<T>(t)` 2) `t` 4) `[std::reference\_wrapper](http://en.cppreference.com/w/cpp/utility/functional/reference_wrapper)<const T>(t)` 5) `t` 3,6) rvalue reference wrapper is deleted. ### Example ``` #include <functional> #include <iostream> void f(int& n1, int& n2, const int& n3) { std::cout << "In function: " << n1 << ' ' << n2 << ' ' << n3 << '\n'; ++n1; // increments the copy of n1 stored in the function object ++n2; // increments the main()'s n2 // ++n3; // compile error } int main() { int n1 = 1, n2 = 2, n3 = 3; std::function<void()> bound_f = std::bind(f, n1, std::ref(n2), std::cref(n3)); n1 = 10; n2 = 11; n3 = 12; std::cout << "Before function: " << n1 << ' ' << n2 << ' ' << n3 << '\n'; bound_f(); std::cout << "After function: " << n1 << ' ' << n2 << ' ' << n3 << '\n'; } ``` Output: ``` Before function: 10 11 12 In function: 1 11 12 After function: 10 12 12 ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 3146](https://cplusplus.github.io/LWG/issue3146) | C++11 | unwrapping overloads sometimes led to error | made always valid | ### See also | | | | --- | --- | | [reference\_wrapper](reference_wrapper "cpp/utility/functional/reference wrapper") (C++11) | [CopyConstructible](../../named_req/copyconstructible "cpp/named req/CopyConstructible") and [CopyAssignable](../../named_req/copyassignable "cpp/named req/CopyAssignable") reference wrapper (class template) | cpp std::less std::less ========= | Defined in header `[<functional>](../../header/functional "cpp/header/functional")` | | | | --- | --- | --- | | ``` template< class T > struct less; ``` | | (until C++14) | | ``` template< class T = void > struct less; ``` | | (since C++14) | Function object for performing comparisons. Unless specialized, invokes `operator<` on type `T`. ### Implementation-defined strict total order over pointers A specialization of `std::less` for any pointer type yields the implementation-defined strict total order, even if the built-in `<` operator does not. The implementation-defined strict total order is consistent with the partial order imposed by built-in comparison operators (`<=>`, (since C++20)`<`, `>`, `<=`, and `>=`), and consistent among following standard function objects: * `std::less`, `[std::greater](greater "cpp/utility/functional/greater")`, `[std::less\_equal](less_equal "cpp/utility/functional/less equal")`, and `[std::greater\_equal](greater_equal "cpp/utility/functional/greater equal")`, when the template argument is a pointer type or `void` (since C++14) | | | | --- | --- | | * [`std::ranges::equal_to`](ranges/equal_to "cpp/utility/functional/ranges/equal to"), [`std::ranges::not_equal_to`](ranges/not_equal_to "cpp/utility/functional/ranges/not equal to"), [`std::ranges::less`](ranges/less "cpp/utility/functional/ranges/less"), [`std::ranges::greater`](ranges/greater "cpp/utility/functional/ranges/greater"), [`std::ranges::less_equal`](ranges/less_equal "cpp/utility/functional/ranges/less equal"), [`std::ranges::greater_equal`](ranges/greater_equal "cpp/utility/functional/ranges/greater equal"), and `[std::compare\_three\_way](../compare/compare_three_way "cpp/utility/compare/compare three way")` | (since C++20) | ### Specializations | | | | --- | --- | | [less<void>](less_void "cpp/utility/functional/less void") (C++14) | function object implementing `x < y` deducing argument and return types (class template specialization) | ### Member types | Type | Definition | | --- | --- | | `result_type` (deprecated in C++17)(removed in C++20) | `bool` | | `first_argument_type` (deprecated in C++17)(removed in C++20) | `T` | | `second_argument_type` (deprecated in C++17)(removed in C++20) | `T` | | | | | --- | --- | | These member types are obtained via publicly inheriting `[std::binary\_function](http://en.cppreference.com/w/cpp/utility/functional/binary_function)<T, T, bool>`. | (until C++11) | ### Member functions | | | | --- | --- | | operator() | checks whether the first argument is *less* than the second (public member function) | std::less::operator() ---------------------- | | | | | --- | --- | --- | | ``` bool operator()( const T& lhs, const T& rhs ) const; ``` | | (until C++14) | | ``` constexpr bool operator()( const T& lhs, const T& rhs ) const; ``` | | (since C++14) | Checks whether `lhs` is *less* than `rhs`. ### Parameters | | | | | --- | --- | --- | | lhs, rhs | - | values to compare | ### Return value For `T` which is not a pointer type, `true` if `lhs < rhs`, `false` otherwise. For `T` which is a pointer type, `true` if `lhs` precedes `rhs` in the implementation-defined strict total order, `false` otherwise. ### Exceptions May throw implementation-defined exceptions. ### Possible implementation | | | --- | | ``` constexpr bool operator()(const T &lhs, const T &rhs) const { return lhs < rhs; // assumes that the implementation uses a flat address space } ``` | ### Example ``` #include <functional> #include <iostream> template <typename A, typename B, typename C = std::less<>> bool fun(A a, B b, C cmp = C{}) { return cmp(a, b); } int main() { std::cout << std::boolalpha << fun(1, 2) << ' ' // true << fun(1.0, 1) << ' ' // false << fun(1, 2.0) << ' ' // true << std::less<int>{}(5, 5.6) << ' ' // false: 5 < 5 (warn: implicit conversion) << std::less<double>{}(5, 5.6) << ' ' // true: 5.0 < 5.6 << std::less<int>{}(5.6, 5.7) << ' ' // false: 5 < 5 (warn: implicit conversion) << std::less{}(5, 5.6) << ' ' // true: less<void>: 5.0 < 5.6 << '\n'; } ``` Output: ``` true false true false true false true ``` ### See also | | | | --- | --- | | [equal\_to](equal_to "cpp/utility/functional/equal to") | function object implementing `x == y` (class template) | | [greater](greater "cpp/utility/functional/greater") | function object implementing `x > y` (class template) | | [ranges::less](ranges/less "cpp/utility/functional/ranges/less") (C++20) | function object implementing `x < y` (class) | cpp std::invoke, std::invoke_r std::invoke, std::invoke\_r =========================== | Defined in header `[<functional>](../../header/functional "cpp/header/functional")` | | | | --- | --- | --- | | | (1) | | | ``` template< class F, class... Args > std::invoke_result_t<F, Args...> invoke( F&& f, Args&&... args ) noexcept(/* see below */); ``` | (since C++17) (until C++20) | | ``` template< class F, class... Args > constexpr std::invoke_result_t<F, Args...> invoke( F&& f, Args&&... args ) noexcept(/* see below */); ``` | (since C++20) | | ``` template< class R, class F, class... Args > constexpr R invoke_r( F&& f, Args&&... args ) noexcept(/* see below */); ``` | (2) | (since C++23) | 1) Invoke the [Callable](../../named_req/callable "cpp/named req/Callable") object `f` with the parameters `args`. As by `INVOKE([std::forward](http://en.cppreference.com/w/cpp/utility/forward)<F>(f), [std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Args>(args)...)`. This overload participates in overload resolution only if `[std::is\_invocable\_v](http://en.cppreference.com/w/cpp/types/is_invocable)<F, Args...>` is `true`. 2) Same as (1), except that the result is implicitly converted to `R` if `R` is not possibly cv-qualified `void`, or discarded otherwise. This overload participates in overload resolution only if `[std::is\_invocable\_r\_v](http://en.cppreference.com/w/cpp/types/is_invocable)<R, F, Args...>` is `true`. The operation *INVOKE(f, t1, t2, ..., tN)* is defined as follows: * If `f` is a [pointer to member function](../../language/pointer#Pointers_to_member_functions "cpp/language/pointer") of class `T`: + If `[std::is\_base\_of](http://en.cppreference.com/w/cpp/types/is_base_of)<T, [std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<decltype(t1)>>::value` is `true`, then `INVOKE(f, t1, t2, ..., tN)` is equivalent to `(t1.*f)(t2, ..., tN)` + If `[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<decltype(t1)>` is a specialization of `[std::reference\_wrapper](reference_wrapper "cpp/utility/functional/reference wrapper")`, then `INVOKE(f, t1, t2, ..., tN)` is equivalent to `(t1.get().*f)(t2, ..., tN)` + If `t1` does not satisfy the previous items, then `INVOKE(f, t1, t2, ..., tN)` is equivalent to `((*t1).*f)(t2, ..., tN)`. * Otherwise, if N == 1 and `f` is a [pointer to data member](../../language/pointer#Pointers_to_data_members "cpp/language/pointer") of class `T`: + If `[std::is\_base\_of](http://en.cppreference.com/w/cpp/types/is_base_of)<T, [std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<decltype(t1)>>::value` is `true`, then `INVOKE(f, t1)` is equivalent to `t1.*f` + If `[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<decltype(t1)>` is a specialization of `[std::reference\_wrapper](reference_wrapper "cpp/utility/functional/reference wrapper")`, then `INVOKE(f, t1)` is equivalent to `t1.get().*f` + If `t1` does not satisfy the previous items, then `INVOKE(f, t1)` is equivalent to `(*t1).*f` * Otherwise, `INVOKE(f, t1, t2, ..., tN)` is equivalent to `f(t1, t2, ..., tN)` (that is, `f` is a [FunctionObject](../../named_req/functionobject "cpp/named req/FunctionObject")) ### Parameters | | | | | --- | --- | --- | | f | - | [Callable](../../named_req/callable "cpp/named req/Callable") object to be invoked | | args | - | arguments to pass to `f` | ### Return value 1) The value returned by `f`. 2) The value returned by `f`, implicitly converted to `R`, if `R` is not `void`. None otherwise. ### Exceptions 1) [`noexcept`](../../language/noexcept_spec "cpp/language/noexcept spec") specification: `noexcept([std::is\_nothrow\_invocable\_v](http://en.cppreference.com/w/cpp/types/is_invocable)<F, Args...>)` 2) [`noexcept`](../../language/noexcept_spec "cpp/language/noexcept spec") specification: `noexcept([std::is\_nothrow\_invocable\_r\_v](http://en.cppreference.com/w/cpp/types/is_invocable)<R, F, Args...>)` ### Possible implementation | First version | | --- | | ``` namespace detail { template<class> constexpr bool is_reference_wrapper_v = false; template<class U> constexpr bool is_reference_wrapper_v<std::reference_wrapper<U>> = true; template<class C, class Pointed, class T1, class... Args> constexpr decltype(auto) invoke_memptr(Pointed C::* f, T1&& t1, Args&&... args) { if constexpr (std::is_function_v<Pointed>) { if constexpr (std::is_base_of_v<C, std::decay_t<T1>>) return (std::forward<T1>(t1).*f)(std::forward<Args>(args)...); else if constexpr (is_reference_wrapper_v<std::decay_t<T1>>) return (t1.get().*f)(std::forward<Args>(args)...); else return ((*std::forward<T1>(t1)).*f)(std::forward<Args>(args)...); } else { static_assert(std::is_object_v<Pointed> && sizeof...(args) == 0); if constexpr (std::is_base_of_v<C, std::decay_t<T1>>) return std::forward<T1>(t1).*f; else if constexpr (is_reference_wrapper_v<std::decay_t<T1>>) return t1.get().*f; else return (*std::forward<T1>(t1)).*f; } } } // namespace detail template<class F, class... Args> constexpr std::invoke_result_t<F, Args...> invoke(F&& f, Args&&... args) noexcept(std::is_nothrow_invocable_v<F, Args...>) { if constexpr (std::is_member_pointer_v<std::decay_t<F>>) return detail::invoke_memptr(f, std::forward<Args>(args)...); else return std::forward<F>(f)(std::forward<Args>(args)...); } ``` | | Second version | | ``` template<class R, class F, class... Args> requires std::is_invocable_r_v<R, F, Args...> constexpr R invoke_r(F&& f, Args&&... args) noexcept(std::is_nothrow_invocable_r_v<R, F, Args...>) { if constexpr (std::is_void_v<R>) std::invoke(std::forward<F>(f), std::forward<Args>(args)...); else return std::invoke(std::forward<F>(f), std::forward<Args>(args)...); } ``` | ### Notes | [Feature-test](../feature_test "cpp/utility/feature test") macro | Value | Std | Comment | | --- | --- | --- | --- | | [`__cpp_lib_invoke`](../../feature_test#Library_features "cpp/feature test") | `201411L` | (C++17) | for `std::invoke` | | [`__cpp_lib_invoke_r`](../../feature_test#Library_features "cpp/feature test") | `202106L` | (C++23) | for `std::invoke_r` | ### Example ``` #include <functional> #include <iostream> #include <type_traits> struct Foo { Foo(int num) : num_(num) {} void print_add(int i) const { std::cout << num_+i << '\n'; } int num_; }; void print_num(int i) { std::cout << i << '\n'; } struct PrintNum { void operator()(int i) const { std::cout << i << '\n'; } }; int main() { // invoke a free function std::invoke(print_num, -9); // invoke a lambda std::invoke([]() { print_num(42); }); // invoke a member function const Foo foo(314159); std::invoke(&Foo::print_add, foo, 1); // invoke (access) a data member std::cout << "num_: " << std::invoke(&Foo::num_, foo) << '\n'; // invoke a function object std::invoke(PrintNum(), 18); # if defined(__cpp_lib_invoke_r) auto add = [](int x, int y) { return x + y; }; auto ret = std::invoke_r<float>(add, 11, 22); static_assert(std::is_same<decltype(ret), float>()); std::cout << ret << '\n'; std::invoke_r<void>(print_num, 44); # endif } ``` Possible output: ``` -9 42 314160 num_: 314159 18 33 44 ``` ### See also | | | | --- | --- | | [mem\_fn](mem_fn "cpp/utility/functional/mem fn") (C++11) | creates a function object out of a pointer to a member (function template) | | [result\_ofinvoke\_result](../../types/result_of "cpp/types/result of") (C++11)(removed in C++20)(C++17) | deduces the result type of invoking a callable object with a set of arguments (class template) | | [is\_invocableis\_invocable\_ris\_nothrow\_invocableis\_nothrow\_invocable\_r](../../types/is_invocable "cpp/types/is invocable") (C++17) | checks if a type can be invoked (as if by `std::invoke`) with the given argument types (class template) | | [apply](../apply "cpp/utility/apply") (C++17) | calls a function with a tuple of arguments (function template) |
programming_docs
cpp std::mem_fun_ref std::mem\_fun\_ref ================== | Defined in header `[<functional>](../../header/functional "cpp/header/functional")` | | | | --- | --- | --- | | ``` template< class Res, class T > std::mem_fun_ref_t<Res,T> mem_fun_ref( Res (T::*f)() ); ``` | (1) | (deprecated in C++11) (removed in C++17) | | ``` template< class Res, class T > std::const_mem_fun_ref_t<Res,T> mem_fun_ref( Res (T::*f)() const ); ``` | (1) | (deprecated in C++11) (removed in C++17) | | ``` template< class Res, class T, class Arg > std::mem_fun1_ref_t<Res,T,Arg> mem_fun_ref( Res (T::*f)(Arg) ); ``` | (2) | (deprecated in C++11) (removed in C++17) | | ``` template< class Res, class T, class Arg > std::const_mem_fun1_ref_t<Res,T,Arg> mem_fun_ref( Res (T::*f)(Arg) const ); ``` | (2) | (deprecated in C++11) (removed in C++17) | Creates a member function wrapper object, deducing the target type from the template arguments. The wrapper object expects a reference to an object of type `T` as the first parameter to its `operator()`. 1) Effectively calls `[std::mem\_fun\_ref\_t](http://en.cppreference.com/w/cpp/utility/functional/mem_fun_ref_t)<S,T>(f)` or `[std::const\_mem\_fun\_ref\_t](http://en.cppreference.com/w/cpp/utility/functional/mem_fun_ref_t)<S,T>(f)`. 2) Effectively calls `[std::mem\_fun1\_ref\_t](http://en.cppreference.com/w/cpp/utility/functional/mem_fun_ref_t)<S,T>(f)` or `[std::const\_mem\_fun1\_ref\_t](http://en.cppreference.com/w/cpp/utility/functional/mem_fun_ref_t)<S,T>(f)`. This function and the related types were deprecated in C++11 and removed in C++17 in favor of the more general `[std::mem\_fn](mem_fn "cpp/utility/functional/mem fn")` and `[std::bind](bind "cpp/utility/functional/bind")`, both of which create callable adaptor-compatible function objects from member functions. ### Parameters | | | | | --- | --- | --- | | f | - | pointer to a member function to create a wrapper for | ### Return value A function object wrapping `f`. ### Exceptions May throw implementation-defined exceptions. ### Notes The difference between `[std::mem\_fun](http://en.cppreference.com/w/cpp/utility/functional/mem_fun)` and `std::mem_fun_ref` is that the former produces an function wrapper that expects a pointer to an object, whereas the latter -- a reference. ### Example Uses `std::mem_fun_ref` to bind `[std::string](../../string/basic_string "cpp/string/basic string")`'s member function `[size()](../../string/basic_string/size "cpp/string/basic string/size")`. ``` #include <functional> #include <vector> #include <string> #include <iterator> #include <algorithm> #include <iostream> int main() { std::vector<std::string> v = {"once", "upon", "a", "time"}; std::transform(v.begin(), v.end(), std::ostream_iterator<std::size_t>(std::cout, " "), std::mem_fun_ref(&std::string::size)); } ``` Output: ``` 4 4 1 4 ``` ### See also | | | | --- | --- | | [mem\_fun](mem_fun "cpp/utility/functional/mem fun") (deprecated in C++11)(removed in C++17) | creates a wrapper from a pointer to member function, callable with a pointer to object (function template) | cpp std::placeholders::_1, std::placeholders::_2, ..., std::placeholders::_N std::placeholders::\_1, std::placeholders::\_2, ..., std::placeholders::\_N =========================================================================== | Defined in header `[<functional>](../../header/functional "cpp/header/functional")` | | | | --- | --- | --- | | ``` /*see below*/ _1; /*see below*/ _2; . . /*see below*/ _N; ``` | | | The `std::placeholders` namespace contains the placeholder objects `[_1, ..., _N]` where `N` is an implementation defined maximum number. When used as an argument in a `[std::bind](bind "cpp/utility/functional/bind")` expression, the placeholder objects are stored in the generated function object, and when that function object is invoked with unbound arguments, each placeholder `_N` is replaced by the corresponding Nth unbound argument. | | | | --- | --- | | Each placeholder is declared as if by `extern /*unspecified*/ _1;` | (until C++17) | | Implementations are encouraged to declare the placeholders as if by `inline constexpr /*unspecified*/ _1;`, although declaring them by `extern /*unspecified*/ _1;` is still allowed by the standard. | (since C++17) | The types of the placeholder objects are [DefaultConstructible](../../named_req/defaultconstructible "cpp/named req/DefaultConstructible") and [CopyConstructible](../../named_req/copyconstructible "cpp/named req/CopyConstructible"), their default copy/move constructors do not throw exceptions, and for any placeholder `_N`, the type `[std::is\_placeholder](http://en.cppreference.com/w/cpp/utility/functional/is_placeholder)<decltype(_N)>` is defined, where `[std::is\_placeholder](http://en.cppreference.com/w/cpp/utility/functional/is_placeholder)<decltype(_N)>` is derived from `[std::integral\_constant](http://en.cppreference.com/w/cpp/types/integral_constant)<int, N>`. ### Example The following code shows the creation of function objects with placeholder arguments. ``` #include <functional> #include <string> #include <iostream> void goodbye(const std::string& s) { std::cout << "Goodbye " << s << '\n'; } class Object { public: void hello(const std::string& s) { std::cout << "Hello " << s << '\n'; } }; int main() { using namespace std::placeholders; using ExampleFunction = std::function<void(const std::string&)>; Object instance; std::string str("World"); ExampleFunction f = std::bind(&Object::hello, &instance, _1); f(str); // equivalent to instance.hello(str) f = std::bind(&goodbye, std::placeholders::_1); f(str); // equivalent to goodbye(str) auto lambda = [](std::string pre, char o, int rep, std::string post) { std::cout << pre; while (rep-- > 0) std::cout << o; std::cout << post << '\n'; }; // binding the lambda: std::function<void(std::string, char, int, std::string)> g = std::bind(&decltype(lambda)::operator(), &lambda, _1, _2, _3, _4); g("G", 'o', 'o'-'g', "gol"); } ``` Output: ``` Hello World Goodbye World Goooooooogol ``` ### See also | | | | --- | --- | | [bind](bind "cpp/utility/functional/bind") (C++11) | binds one or more arguments to a function object (function template) | | [is\_placeholder](is_placeholder "cpp/utility/functional/is placeholder") (C++11) | indicates that an object is a standard placeholder or can be used as one (class template) | | [ignore](../tuple/ignore "cpp/utility/tuple/ignore") (C++11) | placeholder to skip an element when unpacking a `tuple` using [`tie`](../tuple/tie "cpp/utility/tuple/tie") (constant) | cpp std::bind std::bind ========= | Defined in header `[<functional>](../../header/functional "cpp/header/functional")` | | | | --- | --- | --- | | | (1) | | | ``` template< class F, class... Args > /*unspecified*/ bind( F&& f, Args&&... args ); ``` | (since C++11) (until C++20) | | ``` template< class F, class... Args > constexpr /*unspecified*/ bind( F&& f, Args&&... args ); ``` | (since C++20) | | | (2) | | | ``` template< class R, class F, class... Args > /*unspecified*/ bind( F&& f, Args&&... args ); ``` | (since C++11) (until C++20) | | ``` template< class R, class F, class... Args > constexpr /*unspecified*/ bind( F&& f, Args&&... args ); ``` | (since C++20) | The function template `bind` generates a forwarding call wrapper for `f`. Calling this wrapper is equivalent to invoking `f` with some of its arguments bound to `args`. ### Parameters | | | | | --- | --- | --- | | f | - | [Callable](../../named_req/callable "cpp/named req/Callable") object (function object, pointer to function, reference to function, pointer to member function, or pointer to data member) that will be bound to some arguments | | args | - | list of arguments to bind, with the unbound arguments replaced by the placeholders `_1, _2, _3...` of namespace `std::placeholders` | ### Return value A function object of unspecified type `T`, for which `[std::is\_bind\_expression](http://en.cppreference.com/w/cpp/utility/functional/is_bind_expression)<T>::value == true`. It has the following members: std::bind *return type* ------------------------ #### Member objects The return type of `std::bind` holds a member object of type `[std::decay](http://en.cppreference.com/w/cpp/types/decay)<F>::type` constructed from `[std::forward](http://en.cppreference.com/w/cpp/utility/forward)<F>(f)`, and one object per each of `args...`, of type `[std::decay](http://en.cppreference.com/w/cpp/types/decay)<Arg_i>::type`, similarly constructed from `[std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Arg_i>(arg_i)`. #### Constructors The return type of `std::bind` is [CopyConstructible](../../named_req/copyconstructible "cpp/named req/CopyConstructible") if all of its member objects (specified above) are CopyConstructible, and is [MoveConstructible](../../named_req/moveconstructible "cpp/named req/MoveConstructible") otherwise. The type defines the following members: | | | | --- | --- | | Member type `result_type` 1) (deprecated in C++17) If `F` is a pointer to function or a pointer to member function, `result_type` is the return type of `F`. If `F` is a class type with nested typedef `result_type`, then `result_type` is `F::result_type`. Otherwise no `result_type` is defined. 2) (deprecated in C++17) `result_type` is exactly `R`. | (until C++20) | #### Member function `operator()` Given an object `g` obtained from an earlier call to `bind`, when it is invoked in a function call expression `g(u1, u2, ... uM)`, an invocation of the stored object takes place, as if by. 1) `INVOKE(fd, [std::forward](http://en.cppreference.com/w/cpp/utility/forward)<V1>(v1), [std::forward](http://en.cppreference.com/w/cpp/utility/forward)<V2>(v2), ..., [std::forward](http://en.cppreference.com/w/cpp/utility/forward)<VN>(vN))`, or 2) `INVOKE<R>(fd, [std::forward](http://en.cppreference.com/w/cpp/utility/forward)<V1>(v1), [std::forward](http://en.cppreference.com/w/cpp/utility/forward)<V2>(v2), ..., [std::forward](http://en.cppreference.com/w/cpp/utility/forward)<VN>(vN))`, where `*INVOKE*` is the operation specified in [Callable](../../named_req/callable "cpp/named req/Callable"), `fd` is a value of type `[std::decay](http://en.cppreference.com/w/cpp/types/decay)<F>::type` the values and types of the bound arguments `v1, v2, ..., vN` are determined as specified below. * If the stored argument `arg` is of type `[std::reference\_wrapper](http://en.cppreference.com/w/cpp/utility/functional/reference_wrapper)<T>` (for example, `[std::ref](ref "cpp/utility/functional/ref")` or `[std::cref](ref "cpp/utility/functional/ref")` was used in the initial call to `bind`), then the argument `vn` in the `*INVOKE*` operation above is `arg.get()` and the type `Vn` in the same call is `T&`: the stored argument is passed by reference into the invoked function object. * If the stored argument `arg` is of type `T` for which `[std::is\_bind\_expression](http://en.cppreference.com/w/cpp/utility/functional/is_bind_expression)<T>::value == true` (for example, another `bind` expression was passed directly into the initial call to `bind`), then `bind` performs function composition: instead of passing the function object that the bind subexpression would return, the subexpression is invoked eagerly, and its return value is passed to the outer invokable object. If the bind subexpression has any placeholder arguments, they are shared with the outer bind (picked out of `u1, u2, ...`). Specifically, the argument `vn` in the `*INVOKE*` operation above is `arg([std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Uj>(uj)...)` and the type `Vn` in the same call is `[std::result\_of](http://en.cppreference.com/w/cpp/types/result_of)<T cv &(Uj&&...)>::type&&` (until C++17)`[std::invoke\_result\_t](http://en.cppreference.com/w/cpp/types/result_of)<T cv &, Uj&&...>&&` (since C++17) (cv qualification is the same as that of `g`). * If the stored argument `arg` is of type `T`, for which `[std::is\_placeholder](http://en.cppreference.com/w/cpp/utility/functional/is_placeholder)<T>::value != 0` (meaning, a placeholder such as `std::placeholders::_1, _2, _3, ...` was used as the argument to the initial call to `bind`), then the argument indicated by the placeholder (`u1` for `_1`, `u2` for `_2`, etc) is passed to the invokable object: the argument `vn` in the `*INVOKE*` operation above is `[std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Uj>(uj)` and the corresponding type `Vn` in the same call is `Uj&&`. * Otherwise, the ordinary stored argument `arg` is passed to the invokable object as lvalue argument: the argument `vn` in the `*INVOKE*` operation above is simply `arg` and the corresponding type `Vn` is `T cv &`, where cv is the same cv-qualification as that of `g`. If some of the arguments that are supplied in the call to `g()` are not matched by any placeholders stored in `g`, the unused arguments are evaluated and discarded. An invocation of `operator()` is [non-throwing](../../language/noexcept "cpp/language/noexcept") or is a [constant subexpression](../../language/constant_expression "cpp/language/constant expression") (since C++20) if and only if so is the underlying `*INVOKE*` operation. `operator()` participates in overload resolution only if the `*INVOKE*` operation is well-formed when treated as an unevaluated operand. If `g` is volatile-qualified (i.e., its cv-qualifiers are either `volatile` or `const volatile`), the program is ill-formed. ### Exceptions Only throws if construction of `[std::decay](http://en.cppreference.com/w/cpp/types/decay)<F>::type` from `[std::forward](http://en.cppreference.com/w/cpp/utility/forward)<F>(f)` throws, or any of the constructors for `[std::decay](http://en.cppreference.com/w/cpp/types/decay)<Arg_i>::type` from the corresponding `[std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Arg_i>(arg_i)` throws where `Arg_i` is the ith type and `arg_i` is the ith argument in `Args... args`. ### Notes As described in [Callable](../../named_req/callable "cpp/named req/Callable"), when invoking a pointer to non-static member function or pointer to non-static data member, the first argument has to be a reference or pointer (including, possibly, smart pointer such as `[std::shared\_ptr](../../memory/shared_ptr "cpp/memory/shared ptr")` and `[std::unique\_ptr](../../memory/unique_ptr "cpp/memory/unique ptr")`) to an object whose member will be accessed. The arguments to bind are copied or moved, and are never passed by reference unless wrapped in `[std::ref](ref "cpp/utility/functional/ref")` or `[std::cref](ref "cpp/utility/functional/ref")`. Duplicate placeholders in the same bind expression (multiple `_1`'s for example) are allowed, but the results are only well defined if the corresponding argument (`u1`) is an lvalue or non-movable rvalue. ### Example ``` #include <random> #include <iostream> #include <memory> #include <functional> void f(int n1, int n2, int n3, const int& n4, int n5) { std::cout << n1 << ' ' << n2 << ' ' << n3 << ' ' << n4 << ' ' << n5 << '\n'; } int g(int n1) { return n1; } struct Foo { void print_sum(int n1, int n2) { std::cout << n1+n2 << '\n'; } int data = 10; }; int main() { using namespace std::placeholders; // for _1, _2, _3... std::cout << "1) argument reordering and pass-by-reference: "; int n = 7; // (_1 and _2 are from std::placeholders, and represent future // arguments that will be passed to f1) auto f1 = std::bind(f, _2, 42, _1, std::cref(n), n); n = 10; f1(1, 2, 1001); // 1 is bound by _1, 2 is bound by _2, 1001 is unused // makes a call to f(2, 42, 1, n, 7) std::cout << "2) achieving the same effect using a lambda: "; n = 7; auto lambda = [&ncref=n, n](auto a, auto b, auto /*unused*/) { f(b, 42, a, ncref, n); }; n = 10; lambda(1, 2, 1001); // same as a call to f1(1, 2, 1001) std::cout << "3) nested bind subexpressions share the placeholders: "; auto f2 = std::bind(f, _3, std::bind(g, _3), _3, 4, 5); f2(10, 11, 12); // makes a call to f(12, g(12), 12, 4, 5); std::cout << "4) bind a RNG with a distribution: "; std::default_random_engine e; std::uniform_int_distribution<> d(0, 10); auto rnd = std::bind(d, e); // a copy of e is stored in rnd for(int n=0; n<10; ++n) std::cout << rnd() << ' '; std::cout << '\n'; std::cout << "5) bind to a pointer to member function: "; Foo foo; auto f3 = std::bind(&Foo::print_sum, &foo, 95, _1); f3(5); std::cout << "6) bind to a mem_fn that is a pointer to member function: "; auto ptr_to_print_sum = std::mem_fn(&Foo::print_sum); auto f4 = std::bind(ptr_to_print_sum, &foo, 95, _1); f4(5); std::cout << "7) bind to a pointer to data member: "; auto f5 = std::bind(&Foo::data, _1); std::cout << f5(foo) << '\n'; std::cout << "8) bind to a mem_fn that is a pointer to data member: "; auto ptr_to_data = std::mem_fn(&Foo::data); auto f6 = std::bind(ptr_to_data, _1); std::cout << f6(foo) << '\n'; std::cout << "9) use smart pointers to call members of the referenced objects: "; std::cout << f6(std::make_shared<Foo>(foo)) << ' ' << f6(std::make_unique<Foo>(foo)) << '\n'; } ``` Output: ``` 1) argument reordering and pass-by-reference: 2 42 1 10 7 2) achieving the same effect using a lambda: 2 42 1 10 7 3) nested bind subexpressions share the placeholders: 12 12 12 4 5 4) bind a RNG with a distribution: 0 1 8 5 5 2 0 7 7 10 5) bind to a pointer to member function: 100 6) bind to a mem_fn that is a pointer to member function: 100 7) bind to a pointer to data member: 10 8) bind to a mem_fn that is a pointer to data member: 10 9) use smart pointers to call members of the referenced objects: 10 10 ``` ### See also | | | | --- | --- | | [bind\_frontbind\_back](bind_front "cpp/utility/functional/bind front") (C++20)(C++23) | bind a variable number of arguments, in order, to a function object (function template) | | [\_1, \_2, \_3, \_4, ...](placeholders "cpp/utility/functional/placeholders") (C++11) | placeholders for the unbound arguments in a `std::bind` expression (constant) | | [mem\_fn](mem_fn "cpp/utility/functional/mem fn") (C++11) | creates a function object out of a pointer to a member (function template) | cpp std::pointer_to_binary_function std::pointer\_to\_binary\_function ================================== | | | | | --- | --- | --- | | ``` template< class Arg1, class Arg2, class Result > class pointer_to_binary_function : public std::binary_function<Arg1, Arg2, Result>; ``` | | (deprecated in C++11) (removed in C++17) | `std::pointer_to_binary_function` is a function object that acts as a wrapper around a binary function. ### Member functions | | | | --- | --- | | (constructor) | constructs a new `pointer_to_binary_function` object with the supplied function (public member function) | | operator() | calls the stored function (public member function) | std::pointer\_to\_binary\_function::pointer\_to\_binary\_function ------------------------------------------------------------------ | | | | | --- | --- | --- | | ``` explicit pointer_to_binary_function( Result (*f)(Arg1,Arg2) ); ``` | | | Constructs a `pointer_to_binary_function` function object with the stored function `f`. ### Parameters | | | | | --- | --- | --- | | f | - | pointer to a function to store | std::pointer\_to\_binary\_function::operator() ----------------------------------------------- | | | | | --- | --- | --- | | ``` Result operator()( Arg1 x1, Arg2 x2 ) const; ``` | | | Calls the stored function. ### Parameters | | | | | --- | --- | --- | | x1, x2 | - | arguments to pass to the function | ### Return value The value returned by the called function. ### See also | | | | --- | --- | | [pointer\_to\_unary\_function](pointer_to_unary_function "cpp/utility/functional/pointer to unary function") (deprecated in C++11)(removed in C++17) | adaptor-compatible wrapper for a pointer to unary function (class template) | | [ptr\_fun](ptr_fun "cpp/utility/functional/ptr fun") (deprecated in C++11)(removed in C++17) | creates an adaptor-compatible function object wrapper from a pointer to function (function template) |
programming_docs
cpp std::identity std::identity ============= | Defined in header `[<functional>](../../header/functional "cpp/header/functional")` | | | | --- | --- | --- | | ``` struct identity; ``` | | (since C++20) | `std::identity` is a function object type whose `operator()` returns its argument unchanged. ### Member types | Member type | Definition | | --- | --- | | `is_transparent` | /\* unspecified \*/ | ### Member functions | | | | --- | --- | | **operator()** | returns the argument unchanged (public member function) | std::identity::operator() -------------------------- | | | | | --- | --- | --- | | ``` template< class T> constexpr T&& operator()( T&& t ) const noexcept; ``` | | | Returns `[std::forward](http://en.cppreference.com/w/cpp/utility/forward)<T>(t)`. ### Parameters | | | | | --- | --- | --- | | t | - | argument to return | ### Return value `[std::forward](http://en.cppreference.com/w/cpp/utility/forward)<T>(t)`. ### Notes The member type `is_transparent` indicates to the caller that this function object is a *transparent* function object: it accepts arguments of arbitrary types and uses perfect forwarding, which avoids unnecessary copying and conversion when the function object is used in heterogeneous context, or with rvalue arguments. In particular, template functions such as `[std::set::find](../../container/set/find "cpp/container/set/find")` and `[std::set::lower\_bound](../../container/set/lower_bound "cpp/container/set/lower bound")` make use of this member type on their `Compare` types. `std::identity` serves as the default projection in [constrained algorithms](../../algorithm/ranges "cpp/algorithm/ranges"). Its direct usage is usually not needed. ### Example ``` #include <algorithm> #include <functional> #include <iostream> #include <ranges> #include <string> #include <vector> struct Pair { int n; std::string s; friend std::ostream& operator<< (std::ostream& os, const Pair& p) { return os << "{ " << p.n << ", " << p.s << " }"; } }; // A range-printer that can print projected (modified) elements of a range. template <std::ranges::input_range R, typename Projection = std::identity> //<- Notice the default projection void print(std::string_view const rem, R&& r, Projection proj = {}) { std::cout << rem << "{ "; std::ranges::for_each(r, [](const auto& o){ std::cout << o << ' '; }, proj); std::cout << "}\n"; } int main() { const std::vector<Pair> v{ {1, "one"}, {2, "two"}, {3, "three"} }; print("Print using std::identity as a projection: ", v); print("Project the Pair::n: ", v, &Pair::n); print("Project the Pair::s: ", v, &Pair::s); print("Print using custom closure as a projection: ", v, [](Pair const& p) { return std::to_string(p.n) + ':' + p.s; }); } ``` Output: ``` Print using std::identity as a projection: { { 1, one } { 2, two } { 3, three } } Project the Pair::n: { 1 2 3 } Project the Pair::s: { one two three } Print using custom closure as a projection: { 1:one 2:two 3:three } ``` ### See also | | | | --- | --- | | [type\_identity](../../types/type_identity "cpp/types/type identity") (C++20) | returns the type argument unchanged (class template) | cpp std::ptr_fun std::ptr\_fun ============= | Defined in header `[<functional>](../../header/functional "cpp/header/functional")` | | | | --- | --- | --- | | ``` template< class Arg, class Result > std::pointer_to_unary_function<Arg,Result> ptr_fun( Result (*f)(Arg) ); ``` | (1) | (deprecated in C++11) (removed in C++17) | | ``` template< class Arg1, class Arg2, class Result > std::pointer_to_binary_function<Arg1,Arg2,Result> ptr_fun( Result (*f)(Arg1, Arg2) ); ``` | (2) | (deprecated in C++11) (removed in C++17) | Creates a function wrapper object (either `[std::pointer\_to\_unary\_function](http://en.cppreference.com/w/cpp/utility/functional/pointer_to_unary_function)` or `[std::pointer\_to\_binary\_function](http://en.cppreference.com/w/cpp/utility/functional/pointer_to_binary_function)`), deducing the target type from the template arguments. 1) Effectively calls `[std::pointer\_to\_unary\_function](http://en.cppreference.com/w/cpp/utility/functional/pointer_to_unary_function)<Arg,Result>(f)`. 2) Effectively calls `[std::pointer\_to\_binary\_function](http://en.cppreference.com/w/cpp/utility/functional/pointer_to_binary_function)<Arg1,Arg2,Result>(f)`. This function and the related types are deprecated as of C++11 in favor of the more general `[std::function](function "cpp/utility/functional/function")` and `[std::ref](ref "cpp/utility/functional/ref")`, both of which create callable adaptor-compatible function objects from plain functions. ### Parameters | | | | | --- | --- | --- | | f | - | pointer to a function to create a wrapper for | ### Return value A function object wrapping `f`. ### Exceptions May throw implementation-defined exceptions. ### Example ``` #include <iostream> #include <algorithm> #include <functional> #include <string_view> constexpr bool is_vowel(char c) { return std::string_view{"aeoiuAEIOU"}.find(c) != std::string_view::npos; } int main() { std::string_view s = "Hello, world!"; std::ranges::copy_if(s, std::ostreambuf_iterator<char>(std::cout), std::not1(std::ptr_fun(is_vowel))); #if 0 // C++11 alternatives: std::not1(std::cref(is_vowel))); std::not1(std::function<bool(char)>(is_vowel))); [](char c){ return !is_vowel(c); }); // C++17 alternatives: std::not_fn(is_vowel)); #endif } ``` Output: ``` Hll, wrld! ``` ### See also | | | | --- | --- | | [function](function "cpp/utility/functional/function") (C++11) | wraps callable object of any copy constructible type with specified function call signature (class template) | | [move\_only\_function](move_only_function "cpp/utility/functional/move only function") (C++23) | wraps callable object of any type with specified function call signature (class template) | | [invokeinvoke\_r](invoke "cpp/utility/functional/invoke") (C++17)(C++23) | invokes any [Callable](../../named_req/callable "cpp/named req/Callable") object with given arguments and possibility to specify return type (since C++23) (function template) | | [not\_fn](not_fn "cpp/utility/functional/not fn") (C++17) | Creates a function object that returns the complement of the result of the function object it holds (function template) | cpp std::not1 std::not1 ========= | Defined in header `[<functional>](../../header/functional "cpp/header/functional")` | | | | --- | --- | --- | | ``` template< class Predicate > std::unary_negate<Predicate> not1(const Predicate& pred); ``` | | (until C++14) | | ``` template< class Predicate > constexpr std::unary_negate<Predicate> not1(const Predicate& pred); ``` | | (since C++14) (deprecated in C++17) (removed in C++20) | `not1` is a helper function to create a function object that returns the complement of the unary predicate function passed. The function object created is of type `[std::unary\_negate](http://en.cppreference.com/w/cpp/utility/functional/unary_negate)<Predicate>`. The unary predicate type must define a member type, `argument_type`, that is convertible to the predicate's parameter type. The unary function objects obtained from `[std::ref](ref "cpp/utility/functional/ref")`, `[std::cref](ref "cpp/utility/functional/ref")`, `[std::negate](negate "cpp/utility/functional/negate")`, `[std::logical\_not](logical_not "cpp/utility/functional/logical not")`, `[std::mem\_fn](mem_fn "cpp/utility/functional/mem fn")`, `[std::function](function "cpp/utility/functional/function")`, `[std::hash](../hash "cpp/utility/hash")`, or from another call to `std::not1` have this type defined, as are function objects derived from the deprecated `[std::unary\_function](unary_function "cpp/utility/functional/unary function")`. ### Parameters | | | | | --- | --- | --- | | pred | - | unary predicate | ### Return value `std::not1` returns an object of type `[std::unary\_negate](http://en.cppreference.com/w/cpp/utility/functional/unary_negate)<Predicate>`, constructed with `pred`. ### Exceptions None. ### Example ``` #include <algorithm> #include <numeric> #include <iterator> #include <functional> #include <iostream> #include <vector> struct LessThan7 : std::unary_function<int, bool> { bool operator()(int i) const { return i < 7; } }; int main() { std::vector<int> v(10); std::iota(begin(v), end(v), 0); std::cout << std::count_if(begin(v), end(v), std::not1(LessThan7())) << "\n"; //same as above, but using `std::function` std::function<bool(int)> less_than_9 = [](int x){ return x < 9; }; std::cout << std::count_if(begin(v), end(v), std::not1(less_than_9)) << "\n"; } ``` Output: ``` 3 1 ``` ### See also | | | | --- | --- | | [not\_fn](not_fn "cpp/utility/functional/not fn") (C++17) | Creates a function object that returns the complement of the result of the function object it holds (function template) | | [unary\_negate](unary_negate "cpp/utility/functional/unary negate") (deprecated in C++17)(removed in C++20) | wrapper function object returning the complement of the unary predicate it holds (class template) | | [function](function "cpp/utility/functional/function") (C++11) | wraps callable object of any copy constructible type with specified function call signature (class template) | | [move\_only\_function](move_only_function "cpp/utility/functional/move only function") (C++23) | wraps callable object of any type with specified function call signature (class template) | | [not2](not2 "cpp/utility/functional/not2") (deprecated in C++17)(removed in C++20) | constructs custom `[std::binary\_negate](binary_negate "cpp/utility/functional/binary negate")` object (function template) | | [ptr\_fun](ptr_fun "cpp/utility/functional/ptr fun") (deprecated in C++11)(removed in C++17) | creates an adaptor-compatible function object wrapper from a pointer to function (function template) | | [unary\_function](unary_function "cpp/utility/functional/unary function") (deprecated in C++11)(removed in C++17) | adaptor-compatible unary function base class (class template) | cpp std::mem_fun_ref_t, std::mem_fun1_ref_t, std::const_mem_fun_ref_t, std::const_mem_fun1_ref_t std::mem\_fun\_ref\_t, std::mem\_fun1\_ref\_t, std::const\_mem\_fun\_ref\_t, std::const\_mem\_fun1\_ref\_t ========================================================================================================== | Defined in header `[<functional>](../../header/functional "cpp/header/functional")` | | | | --- | --- | --- | | ``` template< class S, class T > class mem_fun_ref_t : public unary_function<T,S> { public: explicit mem_fun_ref_t(S (T::*p)()); S operator()(T& p) const; }; ``` | (1) | (deprecated in C++11) (removed in C++17) | | ``` template< class S, class T > class const_mem_fun_ref_t : public unary_function<T,S> { public: explicit const_mem_fun_ref_t(S (T::*p)() const); S operator()(const T& p) const; }; ``` | (2) | (deprecated in C++11) (removed in C++17) | | ``` template< class S, class T, class A > class mem_fun1_ref_t : public binary_function<T,A,S> { public: explicit mem_fun1_ref_t(S (T::*p)(A)); S operator()(T& p, A x) const; }; ``` | (3) | (deprecated in C++11) (removed in C++17) | | ``` template< class S, class T, class A > class const_mem_fun1_ref_t : public binary_function<T,A,S> { public: explicit const_mem_fun1_ref_t(S (T::*p)(A) const); S operator()(const T& p, A x) const; }; ``` | (4) | (deprecated in C++11) (removed in C++17) | Wrapper around a member function pointer. The class instance whose member function to call is passed as a reference to the `operator()`. 1) Wraps a non-const member function with no parameters. 2) Wraps a const member function with no parameters. 3) Wraps a non-const member function with a single parameter. 4) Wraps a const member function with a single parameter. ### See also | | | | --- | --- | | [mem\_fun\_ref](mem_fun_ref "cpp/utility/functional/mem fun ref") (deprecated in C++11)(removed in C++17) | creates a wrapper from a pointer to member function, callable with a reference to object (function template) | | [mem\_fun\_tmem\_fun1\_tconst\_mem\_fun\_tconst\_mem\_fun1\_t](mem_fun_t "cpp/utility/functional/mem fun t") (deprecated in C++11)(removed in C++17) | wrapper for a pointer to nullary or unary member function, callable with a pointer to object (class template) | cpp std::bit_not std::bit\_not ============= | Defined in header `[<functional>](../../header/functional "cpp/header/functional")` | | | | --- | --- | --- | | ``` template< class T = void > struct bit_not; ``` | | (since C++14) | Function object for performing bitwise NOT. Effectively calls `operator~` on type `T`. ### Specializations The standard library provides a specialization of `std::bit_not` when `T` is not specified, which leaves the parameter types and return type to be deduced. | | | | --- | --- | | [bit\_not<void>](bit_not_void "cpp/utility/functional/bit not void") (C++14) | function object implementing `~x` deducing argument and return types (class template specialization) | ### Member types | Type | Definition | | --- | --- | | `result_type` (deprecated in C++17)(removed in C++20) | `T` | | `argument_type` (deprecated in C++17)(removed in C++20) | `T` | | | | | --- | --- | | These member types are obtained via publicly inheriting `[std::unary\_function](http://en.cppreference.com/w/cpp/utility/functional/unary_function)<T, T>`. | (until C++11) | ### Member functions | | | | --- | --- | | operator() | returns the result of bitwise NOT of its argument (public member function) | std::bit\_not::operator() -------------------------- | | | | | --- | --- | --- | | ``` constexpr T operator()( const T& arg ) const; ``` | | | Returns the result of bitwise NOT of `arg`. ### Parameters | | | | | --- | --- | --- | | arg | - | value to compute bitwise NOT of | ### Return value The result of `~arg`. ### Exceptions May throw implementation-defined exceptions. ### Possible implementation | | | --- | | ``` constexpr T operator()(const T& arg) const { return ~arg; } ``` | ### Notes Although `std::bit_not` is added via post-C++11 proposal [N3421](https://wg21.link/N3421), it is treated as a part of the resolution for [LWG issue 660](https://cplusplus.github.io/LWG/issue660) (except for its transparent specialization [`std::bit_not<>`](bit_not_void "cpp/utility/functional/bit not void")) by common implementations, and thus available in their C++98/03 mode. cpp std::unwrap_reference, std::unwrap_ref_decay std::unwrap\_reference, std::unwrap\_ref\_decay =============================================== | Defined in header `[<type\_traits>](../../header/type_traits "cpp/header/type traits")` | | | | --- | --- | --- | | Defined in header `[<functional>](../../header/functional "cpp/header/functional")` | | | | ``` template< class T > struct unwrap_reference; ``` | (1) | (since C++20) | | ``` template< class T > struct unwrap_ref_decay; ``` | (2) | (since C++20) | 1) If `T` is `[std::reference\_wrapper](http://en.cppreference.com/w/cpp/utility/functional/reference_wrapper)<U>` for some type `U`, provides a member typedef `type` that names `U&`; otherwise, provides a member typedef `type` that names `T`. 2) If `T` is `[std::reference\_wrapper](http://en.cppreference.com/w/cpp/utility/functional/reference_wrapper)<U>` for some type `U`, ignoring cv-qualification and referenceness, provides a member typedef `type` that names `U&`; otherwise, provides a member typedef `type` that names `[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<T>`. The behavior of a program that adds specializations for any of the templates described on this page is undefined. ### Member types | Name | Definition | | --- | --- | | `type` | 1) `U&` if `T` is `[std::reference\_wrapper](http://en.cppreference.com/w/cpp/utility/functional/reference_wrapper)<U>`; `T` otherwise. 2) `U&` if `[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<T>` is `[std::reference\_wrapper](http://en.cppreference.com/w/cpp/utility/functional/reference_wrapper)<U>`; `[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<T>` otherwise. | ### Helper types | | | | | --- | --- | --- | | ``` template<class T> using unwrap_reference_t = typename unwrap_reference<T>::type; ``` | (1) | (since C++20) | | ``` template<class T> using unwrap_ref_decay_t = typename unwrap_ref_decay<T>::type; ``` | (2) | (since C++20) | ### Possible implementation | | | --- | | ``` template <class T> struct unwrap_reference { using type = T; }; template <class U> struct unwrap_reference<std::reference_wrapper<U>> { using type = U&; }; template< class T > struct unwrap_ref_decay : std::unwrap_reference<std::decay_t<T>> {}; ``` | ### Notes `std::unwrap_ref_decay` performs the same transformation as used by `[std::make\_pair](../pair/make_pair "cpp/utility/pair/make pair")` and `[std::make\_tuple](../tuple/make_tuple "cpp/utility/tuple/make tuple")`. | [Feature-test](../feature_test "cpp/utility/feature test") macro | | --- | | [`__cpp_lib_unwrap_ref`](../../feature_test#Library_features "cpp/feature test") | ### Example ``` #include <cassert> #include <iostream> #include <functional> #include <type_traits> int main() { static_assert(std::is_same_v<std::unwrap_reference_t<int>, int>); static_assert(std::is_same_v<std::unwrap_reference_t<const int>, const int>); static_assert(std::is_same_v<std::unwrap_reference_t<int&>, int&>); static_assert(std::is_same_v<std::unwrap_reference_t<int&&>, int&&>); static_assert(std::is_same_v<std::unwrap_reference_t<int*>, int*>); { using T = std::reference_wrapper<int>; using X = std::unwrap_reference_t<T>; static_assert(std::is_same_v<X, int&>); } { using T = std::reference_wrapper<int&>; using X = std::unwrap_reference_t<T>; static_assert(std::is_same_v<X, int&>); } static_assert(std::is_same_v<std::unwrap_ref_decay_t<int>, int>); static_assert(std::is_same_v<std::unwrap_ref_decay_t<const int>, int>); static_assert(std::is_same_v<std::unwrap_ref_decay_t<const int&>, int>); { using T = std::reference_wrapper<int&&>; using X = std::unwrap_ref_decay_t<T>; static_assert(std::is_same_v<X, int&>); } { auto reset = []<typename T>(T&& z) { // x = 0; // Error: does not work if T is reference_wrapper<> // converts T&& into T& for ordinary types // converts T&& into U& for reference_wrapper<U> decltype(auto) r = std::unwrap_reference_t<T>(z); std::cout << "r: " << r << '\n'; r = 0; // OK, r has reference type }; int x = 1; reset(x); assert(x == 0); int y = 2; reset(std::ref(y)); assert(y == 0); } } ``` Output: ``` r: 1 r: 2 ``` ### See also | | | | --- | --- | | [reference\_wrapper](reference_wrapper "cpp/utility/functional/reference wrapper") (C++11) | [CopyConstructible](../../named_req/copyconstructible "cpp/named req/CopyConstructible") and [CopyAssignable](../../named_req/copyassignable "cpp/named req/CopyAssignable") reference wrapper (class template) | | [make\_pair](../pair/make_pair "cpp/utility/pair/make pair") | creates a `pair` object of type, defined by the argument types (function template) | | [make\_tuple](../tuple/make_tuple "cpp/utility/tuple/make tuple") (C++11) | creates a `tuple` object of the type defined by the argument types (function template) |
programming_docs
cpp std::not_equal_to std::not\_equal\_to =================== | Defined in header `[<functional>](../../header/functional "cpp/header/functional")` | | | | --- | --- | --- | | ``` template< class T > struct not_equal_to; ``` | | (until C++14) | | ``` template< class T = void > struct not_equal_to; ``` | | (since C++14) | Function object for performing comparisons. Unless specialised, invokes `operator!=` on type `T`. ### Specializations | | | | | | --- | --- | --- | --- | | The standard library provides a specialization of `std::not_equal_to` when `T` is not specified, which leaves the parameter types and return type to be deduced. | | | | --- | --- | | [not\_equal\_to<void>](not_equal_to_void "cpp/utility/functional/not equal to void") (C++14) | function object implementing `x != y` deducing argument and return types (class template specialization) | | (since C++14) | ### Member types | Type | Definition | | --- | --- | | `result_type` (deprecated in C++17)(removed in C++20) | `bool` | | `first_argument_type` (deprecated in C++17)(removed in C++20) | `T` | | `second_argument_type` (deprecated in C++17)(removed in C++20) | `T` | | | | | --- | --- | | These member types are obtained via publicly inheriting `[std::binary\_function](http://en.cppreference.com/w/cpp/utility/functional/binary_function)<T, T, bool>`. | (until C++11) | ### Member functions | | | | --- | --- | | operator() | checks if the arguments are *not equal* (public member function) | std::not\_equal\_to::operator() -------------------------------- | | | | | --- | --- | --- | | ``` bool operator()( const T& lhs, const T& rhs ) const; ``` | | (until C++14) | | ``` constexpr bool operator()( const T& lhs, const T& rhs ) const; ``` | | (since C++14) | Checks whether `lhs` is *not equal* to `rhs`. ### Parameters | | | | | --- | --- | --- | | lhs, rhs | - | values to compare | ### Return value `true` if `lhs != rhs`, `false` otherwise. ### Exceptions May throw implementation-defined exceptions. ### Possible implementation | | | --- | | ``` constexpr bool operator()(const T &lhs, const T &rhs) const { return lhs != rhs; } ``` | ### See also | | | | --- | --- | | [equal](../../algorithm/equal "cpp/algorithm/equal") | determines if two sets of elements are the same (function template) | | [less](less "cpp/utility/functional/less") | function object implementing `x < y` (class template) | | [ranges::not\_equal\_to](ranges/not_equal_to "cpp/utility/functional/ranges/not equal to") (C++20) | function object implementing `x != y` (class) | cpp std::is_placeholder std::is\_placeholder ==================== | Defined in header `[<functional>](../../header/functional "cpp/header/functional")` | | | | --- | --- | --- | | ``` template< class T > struct is_placeholder; ``` | | (since C++11) | If `T` is the type of a standard placeholder (\_1, \_2, \_3, ...), then this template is derived from `[std::integral\_constant](http://en.cppreference.com/w/cpp/types/integral_constant)<int,1>`, `[std::integral\_constant](http://en.cppreference.com/w/cpp/types/integral_constant)<int,2>`, `[std::integral\_constant](http://en.cppreference.com/w/cpp/types/integral_constant)<int,3>`, respectively. If `T` is not a standard placeholder type, this template is derived from `[std::integral\_constant](http://en.cppreference.com/w/cpp/types/integral_constant)<int,0>` The template may be specialized for any user-defined `T` type: the specialization must satisfy [UnaryTypeTrait](../../named_req/unarytypetrait "cpp/named req/UnaryTypeTrait") with *base characteristic* of `[std::integral\_constant](http://en.cppreference.com/w/cpp/types/integral_constant)<int, N>` with `N > 0` to indicate that `T` should be treated as N'th placeholder type. `[std::bind](bind "cpp/utility/functional/bind")` uses `std::is_placeholder` to detect placeholders for unbound arguments. ### Helper variable template | | | | | --- | --- | --- | | ``` template< class T > inline constexpr int is_placeholder_v = is_placeholder<T>::value; ``` | | (since C++17) | Inherited from [std::integral\_constant](../../types/integral_constant "cpp/types/integral constant") ------------------------------------------------------------------------------------------------------- ### Member constants | | | | --- | --- | | value [static] | placeholder value or 0 for non-placeholder types (public static member constant) | ### Member functions | | | | --- | --- | | operator int | converts the object to `int`, returns `value` (public member function) | | operator() (C++14) | returns `value` (public member function) | ### Member types | Type | Definition | | --- | --- | | `value_type` | `int` | | `type` | `[std::integral\_constant](http://en.cppreference.com/w/cpp/types/integral_constant)<int, value>` | ### Example ``` #include <iostream> #include <type_traits> #include <functional> struct My_2 { } my_2; namespace std { template<> struct is_placeholder<My_2> : public integral_constant<int, 2> {}; } int f(int n1, int n2) { return n1+n2; } int main() { std::cout << "Standard placeholder _5 is for the argument number " << std::is_placeholder<decltype(std::placeholders::_5)>::value << '\n'; auto b = std::bind(f, my_2, 2); std::cout << "Adding 2 to 11 selected with a custom placeholder gives " << b(10, 11) // the first argument, namely 10, is ignored << '\n'; } ``` Output: ``` Standard placeholder _5 is for the argument number 5 Adding 2 to 11 selected with a custom placeholder gives 13 ``` ### See also | | | | --- | --- | | [bind](bind "cpp/utility/functional/bind") (C++11) | binds one or more arguments to a function object (function template) | | [\_1, \_2, \_3, \_4, ...](placeholders "cpp/utility/functional/placeholders") (C++11) | placeholders for the unbound arguments in a `std::bind` expression (constant) | cpp std::not2 std::not2 ========= | Defined in header `[<functional>](../../header/functional "cpp/header/functional")` | | | | --- | --- | --- | | ``` template< class Predicate > std::binary_negate<Predicate> not2(const Predicate& pred); ``` | | (until C++14) | | ``` template< class Predicate > constexpr std::binary_negate<Predicate> not2(const Predicate& pred); ``` | | (since C++14) (deprecated in C++17) (removed in C++20) | `not2` is a helper function to create a function object that returns the complement of the binary predicate function passed. The function object created is of type `[std::binary\_negate](http://en.cppreference.com/w/cpp/utility/functional/binary_negate)<Predicate>`. The binary predicate type must define two member types, `first_argument_type` and `second_argument_type`, that are convertible to the predicate's parameter types. The function objects obtained from `[std::owner\_less](../../memory/owner_less "cpp/memory/owner less")`, `[std::ref](ref "cpp/utility/functional/ref")`, `[std::cref](ref "cpp/utility/functional/ref")`, `[std::plus](plus "cpp/utility/functional/plus")`, `[std::minus](minus "cpp/utility/functional/minus")`, `[std::multiplies](multiplies "cpp/utility/functional/multiplies")`, `[std::divides](divides "cpp/utility/functional/divides")`, `[std::modulus](modulus "cpp/utility/functional/modulus")`, `[std::equal\_to](equal_to "cpp/utility/functional/equal to")`, `[std::not\_equal\_to](not_equal_to "cpp/utility/functional/not equal to")`, `[std::greater](greater "cpp/utility/functional/greater")`, `[std::less](less "cpp/utility/functional/less")`, `[std::greater\_equal](greater_equal "cpp/utility/functional/greater equal")`, `[std::less\_equal](less_equal "cpp/utility/functional/less equal")`, `[std::logical\_not](logical_not "cpp/utility/functional/logical not")`, `[std::logical\_or](logical_or "cpp/utility/functional/logical or")`, `[std::bit\_and](bit_and "cpp/utility/functional/bit and")`, `[std::bit\_or](bit_or "cpp/utility/functional/bit or")`, `std::bit_xor`, `[std::mem\_fn](mem_fn "cpp/utility/functional/mem fn")`, `std::map::value_comp`, `std::multimap::value_comp`, `[std::function](function "cpp/utility/functional/function")`, or from another call to `std::not2` have these types defined, as are function objects derived from the deprecated `[std::binary\_function](binary_function "cpp/utility/functional/binary function")`. ### Parameters | | | | | --- | --- | --- | | pred | - | binary predicate | ### Return value `std::not2` returns an object of type `[std::binary\_negate](http://en.cppreference.com/w/cpp/utility/functional/binary_negate)<Predicate>`, constructed with `pred`. ### Exceptions None. ### Example ``` #include <algorithm> #include <functional> #include <iostream> #include <vector> struct old_same : std::binary_function<int, int, bool> { bool operator()(int a, int b) const { return a == b; } }; struct new_same { bool operator()(int a, int b) const { return a == b; } }; bool same_fn(int a, int b) { return a == b; } int main() { std::vector<int> v1{0, 1, 2}; std::vector<int> v2{2, 1, 0}; std::vector<bool> v3(v1.size()); std::cout << "negating a binary_function:\n"; std::transform(v1.begin(), v1.end(), v2.begin(), v3.begin(), std::not2(old_same())); std::cout << std::boolalpha; for (std::size_t i = 0; i < v1.size(); ++i) std::cout << v1[i] << ' ' << v2[i] << ' ' << v3[i] << '\n'; std::cout << "negating a standard functor:\n"; std::transform(v1.begin(), v1.end(), v2.begin(), v3.begin(), std::not2(std::equal_to<int>())); for (std::size_t i = 0; i < v1.size(); ++i) std::cout << v1[i] << ' ' << v2[i] << ' ' << v3[i] << '\n'; std::cout << "negating a std::function:\n"; std::transform(v1.begin(), v1.end(), v2.begin(), v3.begin(), std::not2(std::function<bool(int,int)>(new_same()))); for (std::size_t i = 0; i < v1.size(); ++i) std::cout << v1[i] << ' ' << v2[i] << ' ' << v3[i] << '\n'; std::cout << "negating a std::reference_wrapper:\n"; std::transform(v1.begin(), v1.end(), v2.begin(), v3.begin(), std::not2(std::ref(same_fn))); for (std::size_t i = 0; i < v1.size(); ++i) std::cout << v1[i] << ' ' << v2[i] << ' ' << v3[i] << '\n'; } ``` Output: ``` negating a binary_function: 0 2 true 1 1 false 2 0 true negating a standard functor: 0 2 true 1 1 false 2 0 true negating a std::function: 0 2 true 1 1 false 2 0 true negating a std::reference_wrapper: 0 2 true 1 1 false 2 0 true ``` ### See also | | | | --- | --- | | [not\_fn](not_fn "cpp/utility/functional/not fn") (C++17) | Creates a function object that returns the complement of the result of the function object it holds (function template) | | [binary\_negate](binary_negate "cpp/utility/functional/binary negate") (deprecated in C++17)(removed in C++20) | wrapper function object returning the complement of the binary predicate it holds (class template) | | [function](function "cpp/utility/functional/function") (C++11) | wraps callable object of any copy constructible type with specified function call signature (class template) | | [move\_only\_function](move_only_function "cpp/utility/functional/move only function") (C++23) | wraps callable object of any type with specified function call signature (class template) | | [not1](not1 "cpp/utility/functional/not1") (deprecated in C++17)(removed in C++20) | constructs custom `[std::unary\_negate](unary_negate "cpp/utility/functional/unary negate")` object (function template) | | [ptr\_fun](ptr_fun "cpp/utility/functional/ptr fun") (deprecated in C++11)(removed in C++17) | creates an adaptor-compatible function object wrapper from a pointer to function (function template) | | [binary\_function](binary_function "cpp/utility/functional/binary function") (deprecated in C++11)(removed in C++17) | adaptor-compatible binary function base class (class template) | cpp std::negate std::negate =========== | Defined in header `[<functional>](../../header/functional "cpp/header/functional")` | | | | --- | --- | --- | | ``` template< class T > struct negate; ``` | | (until C++14) | | ``` template< class T = void > struct negate; ``` | | (since C++14) | Function object for performing negation. Effectively calls `operator-` on an instance of type `T`. ### Specializations | | | | | | --- | --- | --- | --- | | The standard library provides a specialization of `std::negate` when `T` is not specified, which leaves the parameter types and return type to be deduced. | | | | --- | --- | | [negate<void>](negate_void "cpp/utility/functional/negate void") (C++14) | function object implementing `-x` deducing argument and return types (class template specialization) | | (since C++14) | ### Member types | Type | Definition | | --- | --- | | `result_type` (deprecated in C++17)(removed in C++20) | `T` | | `argument_type` (deprecated in C++17)(removed in C++20) | `T` | | | | | --- | --- | | These member types are obtained via publicly inheriting `[std::unary\_function](http://en.cppreference.com/w/cpp/utility/functional/unary_function)<T, T>`. | (until C++11) | ### Member functions | | | | --- | --- | | operator() | returns the negation of the argument (public member function) | std::negate::operator() ------------------------ | | | | | --- | --- | --- | | ``` T operator()( const T& arg ) const; ``` | | (until C++14) | | ``` constexpr T operator()( const T& arg ) const; ``` | | (since C++14) | Returns the negation of `arg`. ### Parameters | | | | | --- | --- | --- | | arg | - | value to compute negation of | ### Return value The result of `-arg`. ### Exceptions May throw implementation-defined exceptions. ### Possible implementation | | | --- | | ``` constexpr T operator()(const T &arg) const { return -arg; } ``` | cpp std::move_only_function std::move\_only\_function ========================= | Defined in header `[<functional>](../../header/functional "cpp/header/functional")` | | | | --- | --- | --- | | ``` template< class... > class move_only_function; // not defined ``` | | (since C++23) | | ``` template< class R, class... Args > class move_only_function<R(Args...)>; template< class R, class... Args > class move_only_function<R(Args...) noexcept>; template< class R, class... Args > class move_only_function<R(Args...) &>; template< class R, class... Args > class move_only_function<R(Args...) & noexcept>; template< class R, class... Args > class move_only_function<R(Args...) &&>; template< class R, class... Args > class move_only_function<R(Args...) && noexcept>; template< class R, class... Args > class move_only_function<R(Args...) const>; template< class R, class... Args > class move_only_function<R(Args...) const noexcept>; template< class R, class... Args > class move_only_function<R(Args...) const &>; template< class R, class... Args > class move_only_function<R(Args...) const & noexcept>; template< class R, class... Args > class move_only_function<R(Args...) const &&>; template< class R, class... Args > class move_only_function<R(Args...) const && noexcept>; ``` | | (since C++23) | Class template `std::move_only_function` is a general-purpose polymorphic function wrapper. `std::move_only_function` objects can store and invoke any constructible (not required to be move constructible) [Callable](../../named_req/callable "cpp/named req/Callable") *target* -- functions, [lambda expressions](../../language/lambda "cpp/language/lambda"), [bind expressions](bind "cpp/utility/functional/bind"), or other function objects, as well as pointers to member functions and pointers to member objects. The stored callable object is called the *target* of `std::move_only_function`. If a `std::move_only_function` contains no target, it is called *empty*. Unlike `[std::function](function "cpp/utility/functional/function")`, invoking an *empty* `std::move_only_function` results in undefined behavior. `std::move_only_functions` supports every possible combination of [cv-qualifiers](../../language/member_functions#const-_and_volatile-qualified_member_functions "cpp/language/member functions"), [ref-qualifiers](../../language/member_functions#ref-qualified_member_functions "cpp/language/member functions"), and [noexcept-specifiers](../../language/noexcept_spec "cpp/language/noexcept spec") not including `volatile` provided in its template parameter. These qualifiers and specifier (if any) are added to its [`operator()`](move_only_function/operator() "cpp/utility/functional/move only function/operator()"). `std::move_only_function` satisfies the requirements of [MoveConstructible](../../named_req/moveconstructible "cpp/named req/MoveConstructible") and [MoveAssignable](../../named_req/moveassignable "cpp/named req/MoveAssignable"), but does not satisfy [CopyConstructible](../../named_req/copyconstructible "cpp/named req/CopyConstructible") or [CopyAssignable](../../named_req/copyassignable "cpp/named req/CopyAssignable"). ### Member types | Type | Definition | | --- | --- | | `result_type` | `R` | ### Member functions | | | | --- | --- | | [(constructor)](move_only_function/move_only_function "cpp/utility/functional/move only function/move only function") (C++23) | constructs a new `std::move_only_function` object (public member function) | | [(destructor)](move_only_function/~move_only_function "cpp/utility/functional/move only function/~move only function") (C++23) | destroys a `std::move_only_function` object (public member function) | | [operator=](move_only_function/operator= "cpp/utility/functional/move only function/operator=") (C++23) | replaces or destroys the target (public member function) | | [swap](move_only_function/swap "cpp/utility/functional/move only function/swap") (C++23) | swaps the targets of two `std::move_only_function` objects (public member function) | | [operator bool](move_only_function/operator_bool "cpp/utility/functional/move only function/operator bool") (C++23) | checks if the `std::move_only_function` has a target (public member function) | | [operator()](move_only_function/operator() "cpp/utility/functional/move only function/operator()") (C++23) | invokes the target (public member function) | ### Non-member functions | | | | --- | --- | | [swap(std::move\_only\_function)](move_only_function/swap2 "cpp/utility/functional/move only function/swap2") (C++23) | overloads the `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` algorithm (function) | | [operator==](move_only_function/operator== "cpp/utility/functional/move only function/operator==") (C++23) | compares a `std::move_only_function` with `nullptr` (function) | ### Notes Implementations are recommended to store a callable object of small size within the `std::move_only_function` object. Such small object optimization is effectively required for function pointers and `[std::reference\_wrapper](reference_wrapper "cpp/utility/functional/reference wrapper")` specializations, and can only be applied to types `T` for which `[std::is\_nothrow\_move\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_move_constructible)<T>` is `true`. If a `std::move_only_function` returning a reference is initialized from a function or function object returning a prvalue (including a lambda expression without a trailing-return-type), the program is ill-formed because binding the returned referenced to a temporary object is forbidden. See also [`std::function`](function#Notes "cpp/utility/functional/function") Notes. | [Feature-test](../feature_test "cpp/utility/feature test") macro | Value | Std | | --- | --- | --- | | [`__cpp_lib_move_only_function`](../../feature_test#Library_features "cpp/feature test") | `202110L` | (C++23) | ### Example ### See also | | | | --- | --- | | [function](function "cpp/utility/functional/function") (C++11) | wraps callable object of any copy constructible type with specified function call signature (class template) |
programming_docs
cpp std::greater std::greater ============ | Defined in header `[<functional>](../../header/functional "cpp/header/functional")` | | | | --- | --- | --- | | ``` template< class T > struct greater; ``` | | (until C++14) | | ``` template< class T = void > struct greater; ``` | | (since C++14) | Function object for performing comparisons. Unless specialized, invokes `operator>` on type `T`. ### Implementation-defined strict total order over pointers A specialization of `std::greater` for any pointer type yields the implementation-defined strict total order, even if the built-in `>` operator does not. The implementation-defined strict total order is consistent with the partial order imposed by built-in comparison operators (`<=>`, (since C++20)`<`, `>`, `<=`, and `>=`), and consistent among following standard function objects: * `[std::less](less "cpp/utility/functional/less")`, `std::greater`, `[std::less\_equal](less_equal "cpp/utility/functional/less equal")`, and `[std::greater\_equal](greater_equal "cpp/utility/functional/greater equal")`, when the template argument is a pointer type or `void` (since C++14) | | | | --- | --- | | * [`std::ranges::equal_to`](ranges/equal_to "cpp/utility/functional/ranges/equal to"), [`std::ranges::not_equal_to`](ranges/not_equal_to "cpp/utility/functional/ranges/not equal to"), [`std::ranges::less`](ranges/less "cpp/utility/functional/ranges/less"), [`std::ranges::greater`](ranges/greater "cpp/utility/functional/ranges/greater"), [`std::ranges::less_equal`](ranges/less_equal "cpp/utility/functional/ranges/less equal"), [`std::ranges::greater_equal`](ranges/greater_equal "cpp/utility/functional/ranges/greater equal"), and `[std::compare\_three\_way](../compare/compare_three_way "cpp/utility/compare/compare three way")` | (since C++20) | ### Specializations | | | | --- | --- | | [greater<void>](greater_void "cpp/utility/functional/greater void") (C++14) | function object implementing `x > y` deducing argument and return types (class template specialization) | ### Member types | Type | Definition | | --- | --- | | `result_type` (deprecated in C++17)(removed in C++20) | `bool` | | `first_argument_type` (deprecated in C++17)(removed in C++20) | `T` | | `second_argument_type` (deprecated in C++17)(removed in C++20) | `T` | | | | | --- | --- | | These member types are obtained via publicly inheriting `[std::binary\_function](http://en.cppreference.com/w/cpp/utility/functional/binary_function)<T, T, bool>`. | (until C++11) | ### Member functions | | | | --- | --- | | operator() | checks whether the first argument is *greater* than the second (public member function) | std::greater::operator() ------------------------- | | | | | --- | --- | --- | | ``` bool operator()( const T& lhs, const T& rhs ) const; ``` | | (until C++14) | | ``` constexpr bool operator()( const T& lhs, const T& rhs ) const; ``` | | (since C++14) | Checks whether `lhs` is *greater* than `rhs`. ### Parameters | | | | | --- | --- | --- | | lhs, rhs | - | values to compare | ### Return value For `T` which is not a pointer type, `true` if `lhs > rhs`, `false` otherwise. For `T` which is a pointer type, `true` if `lhs` succeeds `rhs` in the implementation-defined strict total order, `false` otherwise. ### Exceptions May throw implementation-defined exceptions. ### Possible implementation | | | --- | | ``` constexpr bool operator()(const T &lhs, const T &rhs) const { return lhs > rhs; // assumes that the implementation uses a flat address space } ``` | ### See also | | | | --- | --- | | [less](less "cpp/utility/functional/less") | function object implementing `x < y` (class template) | | [ranges::greater](ranges/greater "cpp/utility/functional/ranges/greater") (C++20) | function object implementing `x > y` (class) | cpp std::logical_not std::logical\_not ================= | Defined in header `[<functional>](../../header/functional "cpp/header/functional")` | | | | --- | --- | --- | | ``` template< class T > struct logical_not; ``` | | (until C++14) | | ``` template< class T = void > struct logical_not; ``` | | (since C++14) | Function object for performing logical NOT (logical negation). Effectively calls `operator!` for type `T`. ### Specializations | | | | | | --- | --- | --- | --- | | The standard library provides a specialization of `std::logical_not` when `T` is not specified, which leaves the parameter types and return type to be deduced. | | | | --- | --- | | [logical\_not<void>](logical_not_void "cpp/utility/functional/logical not void") (C++14) | function object implementing `!x` deducing argument and return types (class template specialization) | | (since C++14) | ### Member types | Type | Definition | | --- | --- | | `result_type` (deprecated in C++17)(removed in C++20) | `bool` | | `argument_type` (deprecated in C++17)(removed in C++20) | `T` | | | | | --- | --- | | These member types are obtained via publicly inheriting `[std::unary\_function](http://en.cppreference.com/w/cpp/utility/functional/unary_function)<T, bool>`. | (until C++11) | ### Member functions | | | | --- | --- | | operator() | returns the logical NOT of the argument (public member function) | std::logical\_not::operator() ------------------------------ | | | | | --- | --- | --- | | ``` bool operator()( const T& arg ) const; ``` | | (until C++14) | | ``` constexpr bool operator()( const T& arg ) const; ``` | | (since C++14) | Returns the logical NOT of `arg`. ### Parameters | | | | | --- | --- | --- | | arg | - | value to compute logical NOT of | ### Return value The result of `!arg`. ### Exceptions May throw implementation-defined exceptions. ### Possible implementation | | | --- | | ``` constexpr // since C++14 bool operator()(const T &arg) const { return !arg; } ``` | cpp std::divides std::divides ============ | Defined in header `[<functional>](../../header/functional "cpp/header/functional")` | | | | --- | --- | --- | | ``` template< class T > struct divides; ``` | | (until C++14) | | ``` template< class T = void > struct divides; ``` | | (since C++14) | Function object for performing division. Effectively calls `operator/` on two instances of type `T`. ### Specializations | | | | | | --- | --- | --- | --- | | The standard library provides a specialization of `std::divides` when `T` is not specified, which leaves the parameter types and return type to be deduced. | | | | --- | --- | | [divides<void>](divides_void "cpp/utility/functional/divides void") (C++14) | function object implementing `x / y` deducing argument and return types (class template specialization) | | (since C++14) | ### Member types | Type | Definition | | --- | --- | | `result_type` (deprecated in C++17)(removed in C++20) | `T` | | `first_argument_type` (deprecated in C++17)(removed in C++20) | `T` | | `second_argument_type` (deprecated in C++17)(removed in C++20) | `T` | | | | | --- | --- | | These member types are obtained via publicly inheriting `[std::binary\_function](http://en.cppreference.com/w/cpp/utility/functional/binary_function)<T, T, T>`. | (until C++11) | ### Member functions | | | | --- | --- | | operator() | returns the result of the division of the first argument by the second argument (public member function) | std::divides::operator() ------------------------- | | | | | --- | --- | --- | | ``` T operator()( const T& lhs, const T& rhs ) const; ``` | | (until C++14) | | ``` constexpr T operator()( const T& lhs, const T& rhs ) const; ``` | | (since C++14) | Returns the result of division of `lhs` by `rhs`. ### Parameters | | | | | --- | --- | --- | | lhs, rhs | - | values to divide one by other | ### Return value The result of `lhs / rhs`. ### Exceptions May throw implementation-defined exceptions. ### Possible implementation | | | --- | | ``` constexpr T operator()(const T &lhs, const T &rhs) const { return lhs / rhs; } ``` | cpp std::modulus std::modulus ============ | Defined in header `[<functional>](../../header/functional "cpp/header/functional")` | | | | --- | --- | --- | | ``` template< class T > struct modulus; ``` | | (until C++14) | | ``` template< class T = void > struct modulus; ``` | | (since C++14) | Function object for computing remainders of divisions. Implements `operator%` for type `T`. ### Specializations | | | | | | --- | --- | --- | --- | | The standard library provides a specialization of `std::modulus` when `T` is not specified, which leaves the parameter types and return type to be deduced. | | | | --- | --- | | [modulus<void>](modulus_void "cpp/utility/functional/modulus void") (C++14) | function object implementing `x % y` deducing argument and return types (class template specialization) | | (since C++14) | ### Member types | Type | Definition | | --- | --- | | `result_type` (deprecated in C++17)(removed in C++20) | `T` | | `first_argument_type` (deprecated in C++17)(removed in C++20) | `T` | | `second_argument_type` (deprecated in C++17)(removed in C++20) | `T` | | | | | --- | --- | | These member types are obtained via publicly inheriting `[std::binary\_function](http://en.cppreference.com/w/cpp/utility/functional/binary_function)<T, T, T>`. | (until C++11) | ### Member functions | | | | --- | --- | | operator() | returns the remainder from the division of the first argument by the second argument (public member function) | std::modulus::operator() ------------------------- | | | | | --- | --- | --- | | ``` T operator()( const T& lhs, const T& rhs ) const; ``` | | (until C++14) | | ``` constexpr T operator()( const T& lhs, const T& rhs ) const; ``` | | (since C++14) | Returns the remainder of the division of `lhs` by `rhs`. ### Parameters | | | | | --- | --- | --- | | lhs, rhs | - | values to divide one by another | ### Return value The result of `lhs % rhs`. ### Exceptions May throw implementation-defined exceptions. ### Possible implementation | | | --- | | ``` constexpr T operator()(const T &lhs, const T &rhs) const { return lhs % rhs; } ``` | ### See also | | | | --- | --- | | [fmodfmodffmodl](../../numeric/math/fmod "cpp/numeric/math/fmod") (C++11)(C++11) | remainder of the floating point division operation (function) | | [remainderremainderfremainderl](../../numeric/math/remainder "cpp/numeric/math/remainder") (C++11)(C++11)(C++11) | signed remainder of the division operation (function) | cpp std::mem_fn std::mem\_fn ============ | Defined in header `[<functional>](../../header/functional "cpp/header/functional")` | | | | --- | --- | --- | | ``` template< class M, class T > /*unspecified*/ mem_fn(M T::* pm) noexcept; ``` | | (since C++11) (until C++20) | | ``` template< class M, class T > constexpr /*unspecified*/ mem_fn(M T::* pm) noexcept; ``` | | (since C++20) | Function template `std::mem_fn` generates wrapper objects for pointers to members, which can store, copy, and invoke a [pointer to member](../../language/pointer#Pointers_to_members "cpp/language/pointer"). Both references and pointers (including smart pointers) to an object can be used when invoking a `std::mem_fn`. ### Parameters | | | | | --- | --- | --- | | pm | - | pointer to member that will be wrapped | ### Return value `std::mem_fn` returns a call wrapper of unspecified type that has the following members: std::mem\_fn *return type* --------------------------- | | | | | | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | Member types | type | definition | | --- | --- | | `result_type`(deprecated in C++17) | the return type of `pm` if `pm` is a pointer to member function, not defined for pointer to member object | | `argument_type`(deprecated in C++17) | `T*`, possibly cv-qualified, if `pm` is a pointer to member function taking no arguments | | `first_argument_type`(deprecated in C++17) | `T*` if `pm` is a pointer to member function taking one argument | | `second_argument_type`(deprecated in C++17) | `T1` if `pm` is a pointer to member function taking one argument of type `T1` | | (until C++20) | ### Member function | | | | | --- | --- | --- | | ``` template<class... Args> /* see below */ operator()(Args&&... args) /* cvref-qualifiers */ noexcept(/* see below */); ``` | | (until C++20) | | ``` template<class... Args> constexpr /* see below */ operator()(Args&&... args) /* cvref-qualifiers */ noexcept(/* see below */); ``` | | (since C++20) | Let `fn` be the call wrapper returned by a call to `std::mem_fn` with a pointer to member `pm`. Then the expression `fn(t, a2, ..., aN)` is equivalent to `INVOKE(pm, t, a2, ..., aN)`, where *INVOKE* is the operation defined in [Callable](../../named_req/callable "cpp/named req/Callable"). Thus, the return type of `operator()` is `[std::result\_of](http://en.cppreference.com/w/cpp/types/result_of)<decltype(pm)(Args&&...)>::type`or equivalently `[std::invoke\_result\_t](http://en.cppreference.com/w/cpp/types/result_of)<decltype(pm), Args&&...>`, and the value in noexcept specifier is equal to `[std::is\_nothrow\_invocable\_v](http://en.cppreference.com/w/cpp/types/is_invocable)<decltype(pm), Args&&...>)` (since C++17). Each argument in `args` is perfectly forwarded, as if by `[std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Args>(args)...`. ### Example Use `mem_fn` to store and execute a member function and a member object: ``` #include <functional> #include <iostream> #include <memory> struct Foo { void display_greeting() { std::cout << "Hello, world.\n"; } void display_number(int i) { std::cout << "number: " << i << '\n'; } int add_xy(int x, int y) { return data + x + y; } template <typename... Args> int add_many(Args... args) { return data + (args + ...); } auto add_them(auto... args) { return data + (args + ...); } int data = 7; }; int main() { auto f = Foo{}; auto greet = std::mem_fn(&Foo::display_greeting); greet(f); auto print_num = std::mem_fn(&Foo::display_number); print_num(f, 42); auto access_data = std::mem_fn(&Foo::data); std::cout << "data: " << access_data(f) << '\n'; auto add_xy = std::mem_fn(&Foo::add_xy); std::cout << "add_xy: " << add_xy(f, 1, 2) << '\n'; // Working with smart pointer auto u = std::make_unique<Foo>(); std::cout << "access_data(u): " << access_data(u) << '\n'; std::cout << "add_xy(u, 1, 2): " << add_xy(u, 1, 2) << '\n'; // Working with member function template with parameter pack auto add_many = std::mem_fn(&Foo::add_many<short, int, long>); std::cout << "add_many(u, ...): " << add_many(u, 1, 2, 3) << '\n'; auto add_them = std::mem_fn(&Foo::add_them<short, int, float, double>); std::cout << "add_them(u, ...): " << add_them(u, 5, 7, 10.0f, 13.0) << '\n'; } ``` Output: ``` Hello, world. number: 42 data: 7 add_xy: 10 access_data(u): 7 add_xy(u, 1, 2): 10 add_many(u, ...): 13 add_them(u, ...): 42 ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 2048](https://cplusplus.github.io/LWG/issue2048) | C++11 | unnecessary overloads provided | removed | | [LWG 2489](https://cplusplus.github.io/LWG/issue2489) | C++11 | noexcept not required | required | ### See also | | | | --- | --- | | [function](function "cpp/utility/functional/function") (C++11) | wraps callable object of any copy constructible type with specified function call signature (class template) | | [move\_only\_function](move_only_function "cpp/utility/functional/move only function") (C++23) | wraps callable object of any type with specified function call signature (class template) | | [bind](bind "cpp/utility/functional/bind") (C++11) | binds one or more arguments to a function object (function template) | cpp std::equal_to std::equal\_to ============== | Defined in header `[<functional>](../../header/functional "cpp/header/functional")` | | | | --- | --- | --- | | ``` template< class T > struct equal_to; ``` | | (until C++14) | | ``` template< class T = void > struct equal_to; ``` | | (since C++14) | Function object for performing comparisons. Unless specialised, invokes `operator==` on type `T`. ### Specializations | | | | | | --- | --- | --- | --- | | The standard library provides a specialization of `std::equal_to` when `T` is not specified, which leaves the parameter types and return type to be deduced. | | | | --- | --- | | [equal\_to<void>](equal_to_void "cpp/utility/functional/equal to void") (C++14) | function object implementing `x == y` deducing argument and return types (class template specialization) | | (since C++14) | ### Member types | Type | Definition | | --- | --- | | `result_type` (deprecated in C++17)(removed in C++20) | `bool` | | `first_argument_type` (deprecated in C++17)(removed in C++20) | `T` | | `second_argument_type` (deprecated in C++17)(removed in C++20) | `T` | | | | | --- | --- | | These member types are obtained via publicly inheriting `[std::binary\_function](http://en.cppreference.com/w/cpp/utility/functional/binary_function)<T, T, bool>`. | (until C++11) | ### Member functions | | | | --- | --- | | operator() | checks if the arguments are *equal* (public member function) | std::equal\_to::operator() --------------------------- | | | | | --- | --- | --- | | ``` bool operator()( const T& lhs, const T& rhs ) const; ``` | | (until C++14) | | ``` constexpr bool operator()( const T& lhs, const T& rhs ) const; ``` | | (since C++14) | Checks whether `lhs` is *equal* to `rhs`. ### Parameters | | | | | --- | --- | --- | | lhs, rhs | - | values to compare | ### Return value `true` if `lhs == rhs`, `false` otherwise. ### Exceptions May throw implementation-defined exceptions. ### Possible implementation | | | --- | | ``` constexpr bool operator()(const T &lhs, const T &rhs) const { return lhs == rhs; } ``` | ### See also | | | | --- | --- | | [equal](../../algorithm/equal "cpp/algorithm/equal") | determines if two sets of elements are the same (function template) | | [not\_equal\_to](not_equal_to "cpp/utility/functional/not equal to") | function object implementing `x != y` (class template) | | [less](less "cpp/utility/functional/less") | function object implementing `x < y` (class template) | | [ranges::equal\_to](ranges/equal_to "cpp/utility/functional/ranges/equal to") (C++20) | function object implementing `x == y` (class) | cpp std::unary_negate std::unary\_negate ================== | Defined in header `[<functional>](../../header/functional "cpp/header/functional")` | | | | --- | --- | --- | | ``` template< class Predicate > struct unary_negate : public std::unary_function<Predicate::argument_type, bool>; ``` | | (until C++11) | | ``` template< class Predicate > struct unary_negate; ``` | | (since C++11) (deprecated in C++17) (removed in C++20) | `unary_negate` is a wrapper function object returning the complement of the unary predicate it holds. The unary predicate type must define a member type, `argument_type`, that is convertible to the predicate's parameter type. The unary function objects obtained from `[std::ref](ref "cpp/utility/functional/ref")`, `[std::cref](ref "cpp/utility/functional/ref")`, `[std::negate](negate "cpp/utility/functional/negate")`, `[std::logical\_not](logical_not "cpp/utility/functional/logical not")`, `[std::mem\_fn](mem_fn "cpp/utility/functional/mem fn")`, `[std::function](function "cpp/utility/functional/function")`, `[std::hash](../hash "cpp/utility/hash")`, or from another call to `[std::not1](not1 "cpp/utility/functional/not1")` have this type defined, as are function objects derived from the deprecated `[std::unary\_function](unary_function "cpp/utility/functional/unary function")`. `unary_negate` objects are easily constructed with helper function `[std::not1](not1 "cpp/utility/functional/not1")`. ### Member types | Type | Definition | | --- | --- | | `argument_type` | `Predicate::argument_type` | | `result_type` | `bool` | ### Member functions | | | | --- | --- | | (constructor) | constructs a new unary\_negate object with the supplied predicate (public member function) | | operator() | returns the logical complement of the result of a call to the stored predicate (public member function) | std::unary\_negate::unary\_negate ---------------------------------- | | | | | --- | --- | --- | | ``` explicit unary_negate( Predicate const& pred ); ``` | | (until C++14) | | ``` explicit constexpr unary_negate( Predicate const& pred ); ``` | | (since C++14) | Constructs a `unary_negate` function object with the stored predicate `pred`. ### Parameters | | | | | --- | --- | --- | | pred | - | predicate function object | std::unary\_negate::operator() ------------------------------- | | | | | --- | --- | --- | | ``` bool operator()( argument_type const& x ) const; ``` | | (until C++14) | | ``` constexpr bool operator()( argument_type const& x ) const; ``` | | (since C++14) | Returns the logical complement of the result of calling `pred(x)`. ### Parameters | | | | | --- | --- | --- | | x | - | argument to pass through to predicate | ### Return value The logical complement of the result of calling `pred(x)`. ### Example ``` #include <algorithm> #include <functional> #include <iostream> #include <vector> struct less_than_7 : std::unary_function<int, bool> { bool operator()(int i) const { return i < 7; } }; int main() { std::vector<int> v; for (int i = 0; i < 10; ++i) v.push_back(i); std::unary_negate<less_than_7> not_less_than_7((less_than_7())); std::cout << std::count_if(v.begin(), v.end(), not_less_than_7); /* C++11 solution: // Use std::function<bool (int)> std::function<bool (int)> not_less_than_7 = [](int x)->bool{ return !less_than_7()(x); }; std::cout << std::count_if(v.begin(), v.end(), not_less_than_7); */ } ``` Output: ``` 3 ``` ### See also | | | | --- | --- | | [binary\_negate](binary_negate "cpp/utility/functional/binary negate") (deprecated in C++17)(removed in C++20) | wrapper function object returning the complement of the binary predicate it holds (class template) | | [function](function "cpp/utility/functional/function") (C++11) | wraps callable object of any copy constructible type with specified function call signature (class template) | | [move\_only\_function](move_only_function "cpp/utility/functional/move only function") (C++23) | wraps callable object of any type with specified function call signature (class template) | | [not1](not1 "cpp/utility/functional/not1") (deprecated in C++17)(removed in C++20) | constructs custom `std::unary_negate` object (function template) | | [ptr\_fun](ptr_fun "cpp/utility/functional/ptr fun") (deprecated in C++11)(removed in C++17) | creates an adaptor-compatible function object wrapper from a pointer to function (function template) | | [unary\_function](unary_function "cpp/utility/functional/unary function") (deprecated in C++11)(removed in C++17) | adaptor-compatible unary function base class (class template) |
programming_docs
cpp std::minus std::minus ========== | Defined in header `[<functional>](../../header/functional "cpp/header/functional")` | | | | --- | --- | --- | | ``` template< class T > struct minus; ``` | | (until C++14) | | ``` template< class T = void > struct minus; ``` | | (since C++14) | Function object for performing subtraction. Effectively calls `operator-` on two instances of type `T`. ### Specializations | | | | | | --- | --- | --- | --- | | The standard library provides a specialization of `std::minus` when `T` is not specified, which leaves the parameter types and return type to be deduced. | | | | --- | --- | | [minus<void>](minus_void "cpp/utility/functional/minus void") (C++14) | function object implementing `x - y` deducing argument and return types (class template specialization) | | (since C++14) | ### Member types | Type | Definition | | --- | --- | | `result_type` (deprecated in C++17)(removed in C++20) | `T` | | `first_argument_type` (deprecated in C++17)(removed in C++20) | `T` | | `second_argument_type` (deprecated in C++17)(removed in C++20) | `T` | | | | | --- | --- | | These member types are obtained via publicly inheriting `[std::binary\_function](http://en.cppreference.com/w/cpp/utility/functional/binary_function)<T, T, T>`. | (until C++11) | ### Member functions | | | | --- | --- | | operator() | returns the difference between two arguments (public member function) | std::minus::operator() ----------------------- | | | | | --- | --- | --- | | ``` T operator()( const T& lhs, const T& rhs ) const; ``` | | (until C++14) | | ``` constexpr T operator()( const T& lhs, const T& rhs ) const; ``` | | (since C++14) | Returns the difference between `lhs` and `rhs`. ### Parameters | | | | | --- | --- | --- | | lhs, rhs | - | values to subtract from one another | ### Return value The result of `lhs - rhs`. ### Exceptions May throw implementation-defined exceptions. ### Possible implementation | | | --- | | ``` constexpr T operator()(const T &lhs, const T &rhs) const { return lhs - rhs; } ``` | cpp std::is_bind_expression std::is\_bind\_expression ========================= | Defined in header `[<functional>](../../header/functional "cpp/header/functional")` | | | | --- | --- | --- | | ``` template< class T > struct is_bind_expression; ``` | | (since C++11) | If `T` is the type produced by a call to `[std::bind](bind "cpp/utility/functional/bind")`, this template is derived from `[std::true\_type](../../types/integral_constant "cpp/types/integral constant")`. For any other type, this template is derived from `[std::false\_type](../../types/integral_constant "cpp/types/integral constant")`. This template may be specialized for a user-defined type `T` to implement [UnaryTypeTrait](../../named_req/unarytypetrait "cpp/named req/UnaryTypeTrait") with *base characteristic* of `[std::true\_type](../../types/integral_constant "cpp/types/integral constant")` to indicate that `T` should be treated by `[std::bind](bind "cpp/utility/functional/bind")` as if it were the type of a bind subexpression: when a bind-generated function object is invoked, a bound argument of this type will be invoked as a function object and will be given all the unbound arguments passed to the bind-generated object. ### Helper variable template | | | | | --- | --- | --- | | ``` template< class T > inline constexpr bool is_bind_expression_v = is_bind_expression<T>::value; ``` | | (since C++17) | Inherited from [std::integral\_constant](../../types/integral_constant "cpp/types/integral constant") ------------------------------------------------------------------------------------------------------- ### Member constants | | | | --- | --- | | value [static] | `true` if `T` is a function object generated by `[std::bind](bind "cpp/utility/functional/bind")`, `false` otherwise (public static member constant) | ### Member functions | | | | --- | --- | | operator bool | converts the object to `bool`, returns `value` (public member function) | | operator() (C++14) | returns `value` (public member function) | ### Member types | Type | Definition | | --- | --- | | `value_type` | `bool` | | `type` | `[std::integral\_constant](http://en.cppreference.com/w/cpp/types/integral_constant)<bool, value>` | ### Example ``` #include <iostream> #include <type_traits> #include <functional> struct MyBind { typedef int result_type; int operator()(int a, int b) const { return a + b; } }; namespace std { template<> struct is_bind_expression<MyBind> : public true_type {}; } int f(int n1, int n2) { return n1+n2; } int main() { // as if bind(f, bind(MyBind(), _1, _2), 2) auto b = std::bind(f, MyBind(), 2); std::cout << "Adding 2 to the sum of 10 and 11 gives " << b(10, 11) << '\n'; } ``` Output: ``` Adding 2 to the sum of 10 and 11 gives 23 ``` ### See also | | | | --- | --- | | [bind](bind "cpp/utility/functional/bind") (C++11) | binds one or more arguments to a function object (function template) | cpp std::mem_fun_t, std::mem_fun1_t, std::const_mem_fun_t, std::const_mem_fun1_t std::mem\_fun\_t, std::mem\_fun1\_t, std::const\_mem\_fun\_t, std::const\_mem\_fun1\_t ====================================================================================== | Defined in header `[<functional>](../../header/functional "cpp/header/functional")` | | | | --- | --- | --- | | ``` template< class S, class T > class mem_fun_t : public unary_function<T*,S> { public: explicit mem_fun_t(S (T::*p)()); S operator()(T* p) const; }; ``` | (1) | (deprecated in C++11) (removed in C++17) | | ``` template< class S, class T > class const_mem_fun_t : public unary_function<const T*,S> { public: explicit const_mem_fun_t(S (T::*p)() const); S operator()(const T* p) const; }; ``` | (2) | (deprecated in C++11) (removed in C++17) | | ``` template< class S, class T, class A > class mem_fun1_t : public binary_function<T*,A,S> { public: explicit mem_fun1_t(S (T::*p)(A)); S operator()(T* p, A x) const; }; ``` | (3) | (deprecated in C++11) (removed in C++17) | | ``` template< class S, class T, class A > class const_mem_fun1_t : public binary_function<const T*,A,S> { public: explicit const_mem_fun1_t(S (T::*p)(A) const); S operator()(const T* p, A x) const; }; ``` | (4) | (deprecated in C++11) (removed in C++17) | Wrapper around a member function pointer. The class instance whose member function to call is passed as a pointer to the `operator()`. 1) Wraps a non-const member function with no parameters. 2) Wraps a const member function with no parameters. 3) Wraps a non-const member function with a single parameter. 4) Wraps a const member function with a single parameter. ### See also | | | | --- | --- | | [mem\_fun](mem_fun "cpp/utility/functional/mem fun") (deprecated in C++11)(removed in C++17) | creates a wrapper from a pointer to member function, callable with a pointer to object (function template) | | [mem\_fun\_ref\_tmem\_fun1\_ref\_tconst\_mem\_fun\_ref\_tconst\_mem\_fun1\_ref\_t](mem_fun_ref_t "cpp/utility/functional/mem fun ref t") (deprecated in C++11)(removed in C++17) | wrapper for a pointer to nullary or unary member function, callable with a reference to object (class template) | cpp std::unary_function std::unary\_function ==================== | Defined in header `[<functional>](../../header/functional "cpp/header/functional")` | | | | --- | --- | --- | | ``` template <typename ArgumentType, typename ResultType> struct unary_function; ``` | | (deprecated in C++11) (removed in C++17) | `unary_function` is a base class for creating function objects with one argument. `unary_function` does not define `operator()`; it is expected that derived classes will define this. `unary_function` provides only two types - `argument_type` and `result_type` - defined by the template parameters. Some standard library function object adaptors, such as `[std::not1](not1 "cpp/utility/functional/not1")`, require the function objects they adapt to have certain types defined; `[std::not1](not1 "cpp/utility/functional/not1")` requires the function object being adapted to have a type named `argument_type`. Deriving function objects that take one argument from `unary_function` is an easy way to make them compatible with those adaptors. `unary_function` is deprecated in C++11. ### Member types | Type | Definition | | --- | --- | | `argument_type` | `ArgumentType` | | `result_type` | `ResultType` | ### Example ``` #include <algorithm> #include <functional> #include <iostream> #include <vector> struct less_than_7 : std::unary_function<int, bool> { bool operator()(int i) const { return i < 7; } }; int main() { std::vector<int> v; for (int i = 0; i < 10; ++i) v.push_back(i); std::cout << std::count_if(v.begin(), v.end(), std::not1(less_than_7())); /* C++11 solution: // Cast to std::function<bool (int)> somehow - even with a lambda std::cout << std::count_if(v.begin(), v.end(), std::not1(std::function<bool (int)>([](int i){ return i < 7; })) ); */ } ``` Output: ``` 3 ``` ### See also | | | | --- | --- | | [function](function "cpp/utility/functional/function") (C++11) | wraps callable object of any copy constructible type with specified function call signature (class template) | | [move\_only\_function](move_only_function "cpp/utility/functional/move only function") (C++23) | wraps callable object of any type with specified function call signature (class template) | | [ptr\_fun](ptr_fun "cpp/utility/functional/ptr fun") (deprecated in C++11)(removed in C++17) | creates an adaptor-compatible function object wrapper from a pointer to function (function template) | | [pointer\_to\_unary\_function](pointer_to_unary_function "cpp/utility/functional/pointer to unary function") (deprecated in C++11)(removed in C++17) | adaptor-compatible wrapper for a pointer to unary function (class template) | | [binary\_function](binary_function "cpp/utility/functional/binary function") (deprecated in C++11)(removed in C++17) | adaptor-compatible binary function base class (class template) | cpp std::bind_front, std::bind_back std::bind\_front, std::bind\_back ================================= | Defined in header `[<functional>](../../header/functional "cpp/header/functional")` | | | | --- | --- | --- | | ``` template <class F, class... Args> constexpr /*unspecified*/ bind_front( F&& f, Args&&... args ); ``` | (1) | (since C++20) | | ``` template <class F, class... Args> constexpr /*unspecified*/ bind_back( F&& f, Args&&... args ); ``` | (2) | (since C++23) | Function templates `bind_front` and `bind_back` generate a forwarding call wrapper for `f`. Calling this wrapper is equivalent to invoking `f` with its (1) first or (2) last `sizeof...(Args)` parameters bound to `args`. In other words: * `std::bind_front(f, bound_args...)(call_args...)` is equivalent to `[std::invoke](http://en.cppreference.com/w/cpp/utility/functional/invoke)(f, bound_args..., call_args...)`. * `std::bind_back(f, bound_args...)(call_args...)` is equivalent to `[std::invoke](http://en.cppreference.com/w/cpp/utility/functional/invoke)(f, call_args..., bound_args...)`. The program is ill-formed if any of the following is `false`: * `[std::is\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_constructible)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<F>, F>` * `[std::is\_move\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_move_constructible)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<F>>` * `([std::is\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_constructible)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<Args>, Args> && ...)` * `([std::is\_move\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_move_constructible)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<Args>> && ...)` ### Parameters | | | | | --- | --- | --- | | f | - | [Callable](../../named_req/callable "cpp/named req/Callable") object (function object, pointer to function, reference to function, pointer to member function, or pointer to data member) that will be bound to some arguments | | args | - | list of the arguments to bind to the (1) first or (2) last `sizeof...(Args)` parameters of `f` | | Type requirements | | -`[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<F> and each type in [std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<Args>...` must meet the requirements of [MoveConstructible](../../named_req/moveconstructible "cpp/named req/MoveConstructible"). | ### Return value A function object of type `T` that is unspecified, except that the types of objects returned by two calls to `std::bind_front` or `std::bind_back` with the same arguments are the same. The returned object (call wrapper) has the following properties: *bind-partial return type* --------------------------- Let `*bind-partial*` be either `std::bind_front` or `std::bind_back`. #### Member objects The returned object behaves as if it holds a member object `fd` of type `[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<F>` direct-non-list-initialized from `[std::forward](http://en.cppreference.com/w/cpp/utility/forward)<F>(f)`, and an `[std::tuple](../tuple "cpp/utility/tuple")` object `tup` constructed with `[std::tuple](http://en.cppreference.com/w/cpp/utility/tuple)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<Args>...>([std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Args>(args)...)`, except that the returned object's assignment behavior is unspecified and the names are for exposition only. #### Constructors The return type of `*bind-partial*` behaves as if its copy/move constructors perform a memberwise copy/move. It is [CopyConstructible](../../named_req/copyconstructible "cpp/named req/CopyConstructible") if all of its member objects (specified above) are CopyConstructible, and is [MoveConstructible](../../named_req/moveconstructible "cpp/named req/MoveConstructible") otherwise. #### Member function `operator()` Given an object `G` obtained from an earlier call to `*bind-partial*(f, args...)`, when a glvalue `g` designating `G` is invoked in a function call expression `g(call_args...)`, an invocation of the stored object takes place, as if by. * `[std::invoke](http://en.cppreference.com/w/cpp/utility/functional/invoke)(g.fd, [std::get](http://en.cppreference.com/w/cpp/utility/variant/get)<Ns>(g.tup)..., call_args...)`, when `*bind-partial*` is `std::bind_front`, or by * `[std::invoke](http://en.cppreference.com/w/cpp/utility/functional/invoke)(g.fd, call_args..., [std::get](http://en.cppreference.com/w/cpp/utility/variant/get)<Ns>(g.tup)...)`, when `*bind-partial*` is `std::bind_back`, where + `Ns` is an integer pack `0, 1, ..., (sizeof...(Args) - 1)` + `g` is an lvalue in the `[std::invoke](invoke "cpp/utility/functional/invoke")` expression if it is an lvalue in the call expression, and is an rvalue otherwise. Thus `std::move(g)(call_args...)` can move the bound arguments into the call, where `g(call_args...)` would copy. The program is ill-formed if `g` has volatile-qualified type. The member `operator()` is [`noexcept`](../../language/noexcept "cpp/language/noexcept") if the `[std::invoke](invoke "cpp/utility/functional/invoke")` expression it calls is noexcept (in other words, it preserves the exception specification of the underlying call operator). ### Exceptions Only throws if construction of stored function object or any of the bound arguments throws. ### Notes These function templates are intended to replace `[std::bind](bind "cpp/utility/functional/bind")`. Unlike `std::bind`, they do not support arbitrary argument rearrangement and have no special treatment for nested bind-expressions or `[std::reference\_wrapper](reference_wrapper "cpp/utility/functional/reference wrapper")`s. On the other hand, they pay attention to the value category of the call wrapper object and propagate exception specification of the underlying call operator. As described in `[std::invoke](invoke "cpp/utility/functional/invoke")`, when invoking a pointer to non-static member function or pointer to non-static data member, the first argument has to be a reference or pointer (including, possibly, smart pointer such as `[std::shared\_ptr](../../memory/shared_ptr "cpp/memory/shared ptr")` and `[std::unique\_ptr](../../memory/unique_ptr "cpp/memory/unique ptr")`) to an object whose member will be accessed. The arguments to `std::bind_front` or `std::bind_back` are copied or moved, and are never passed by reference unless wrapped in `[std::ref](ref "cpp/utility/functional/ref")` or `[std::cref](ref "cpp/utility/functional/ref")`. | [Feature-test](../feature_test "cpp/utility/feature test") macro | Value | Std | | --- | --- | --- | | [`__cpp_lib_bind_front`](../../feature_test#Library_features "cpp/feature test") | `201907L` | (C++20) | | [`__cpp_lib_bind_back`](../../feature_test#Library_features "cpp/feature test") | `202202L` | (C++23) | ### Example ``` #include <functional> #include <iostream> int minus(int a, int b) { return a - b; } struct S { int val; int minus(int arg) const noexcept { return val - arg; } }; int main() { auto fifty_minus = std::bind_front(minus, 50); std::cout << fifty_minus (3) << '\n'; // equivalent to `minus(50, 3)` auto member_minus = std::bind_front(&S::minus, S{50}); std::cout << member_minus (3) << '\n'; // equivalent to `S tmp{50}; tmp.minus(3)` // noexcept-specification is preserved! static_assert(! noexcept(fifty_minus (3))); static_assert(noexcept(member_minus (3))); // binding of a lambda auto plus = [](int a, int b) { return a + b; }; auto forty_plus = std::bind_front(plus, 40); std::cout << forty_plus(7) << '\n'; // equivalent to `plus(40, 7)` #ifdef __cpp_lib_bind_back auto madd = [](int a, int b, int c) { return a * b + c; }; auto mul_plus_seven = std::bind_back(madd, 7); std::cout << mul_plus_seven(4, 10) << '\n'; // equivalent to `madd(4, 10, 7)` #endif } ``` Possible output: ``` 47 47 47 47 ``` ### See also | | | | --- | --- | | [bind](bind "cpp/utility/functional/bind") (C++11) | binds one or more arguments to a function object (function template) | | [mem\_fn](mem_fn "cpp/utility/functional/mem fn") (C++11) | creates a function object out of a pointer to a member (function template) | cpp std::binary_function std::binary\_function ===================== | Defined in header `[<functional>](../../header/functional "cpp/header/functional")` | | | | --- | --- | --- | | ``` template< class Arg1, class Arg2, class Result > struct binary_function; ``` | | (deprecated in C++11) (removed in C++17) | `binary_function` is a base class for creating function objects with two arguments. `binary_function` does not define `operator()`; it is expected that derived classes will define this. `binary_function` provides only three types - `first_argument_type`, `second_argument_type` and `result_type` - defined by the template parameters. Some standard library function object adaptors, such as `[std::not2](not2 "cpp/utility/functional/not2")`, require the function objects they adapt to have certain types defined; `[std::not2](not2 "cpp/utility/functional/not2")` requires the function object being adapted to have two types named `first_argument_type` and `second_argument_type`. Deriving function objects that take two arguments from `binary_function` is an easy way to make them compatible with those adaptors. `binary_function` is deprecated in C++11 and removed in C++17. ### Member types | Type | Definition | | --- | --- | | `first_argument_type` | `Arg1` | | `second_argument_type` | `Arg2` | | `result_type` | `Result` | ### Example ``` #include <algorithm> #include <functional> #include <iostream> #include <vector> struct same : std::binary_function<int, int, bool> { bool operator()(int a, int b) const { return a == b; } }; int main() { std::vector<int> v1{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; std::vector<int> v2{10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 }; std::vector<bool> v3(v1.size()); std::transform(v1.begin(), v1.end(), v2.begin(), v3.begin(), std::not2(same())); std::cout << std::boolalpha; for (std::size_t i = 0; i < v1.size(); ++i) std::cout << v1[i] << ' ' << v2[i] << ' ' << v3[i] << '\n'; } ``` Output: ``` 0 10 true 1 9 true 2 8 true 3 7 true 4 6 true 5 5 false 6 4 true 7 3 true 8 2 true 9 1 true 10 0 true ``` ### See also | | | | --- | --- | | [function](function "cpp/utility/functional/function") (C++11) | wraps callable object of any copy constructible type with specified function call signature (class template) | | [move\_only\_function](move_only_function "cpp/utility/functional/move only function") (C++23) | wraps callable object of any type with specified function call signature (class template) | | [ptr\_fun](ptr_fun "cpp/utility/functional/ptr fun") (deprecated in C++11)(removed in C++17) | creates an adaptor-compatible function object wrapper from a pointer to function (function template) | | [pointer\_to\_binary\_function](pointer_to_binary_function "cpp/utility/functional/pointer to binary function") (deprecated in C++11)(removed in C++17) | adaptor-compatible wrapper for a pointer to binary function (class template) | | [unary\_function](unary_function "cpp/utility/functional/unary function") (deprecated in C++11)(removed in C++17) | adaptor-compatible unary function base class (class template) |
programming_docs
cpp std::bit_and std::bit\_and ============= | Defined in header `[<functional>](../../header/functional "cpp/header/functional")` | | | | --- | --- | --- | | ``` template< class T > struct bit_and; ``` | | (until C++14) | | ``` template< class T = void > struct bit_and; ``` | | (since C++14) | Function object for performing bitwise AND. Effectively calls `operator&` on type `T`. ### Specializations | | | | | | --- | --- | --- | --- | | The standard library provides a specialization of `std::bit_and` when `T` is not specified, which leaves the parameter types and return type to be deduced. | | | | --- | --- | | [bit\_and<void>](bit_and_void "cpp/utility/functional/bit and void") (C++14) | function object implementing `x & y` deducing argument and return types (class template specialization) | | (since C++14) | ### Member types | Type | Definition | | --- | --- | | `result_type` (deprecated in C++17)(removed in C++20) | `T` | | `first_argument_type` (deprecated in C++17)(removed in C++20) | `T` | | `second_argument_type` (deprecated in C++17)(removed in C++20) | `T` | | | | | --- | --- | | These member types are obtained via publicly inheriting `[std::binary\_function](http://en.cppreference.com/w/cpp/utility/functional/binary_function)<T, T, T>`. | (until C++11) | ### Member functions | | | | --- | --- | | operator() | returns the result of bitwise AND of two arguments (public member function) | std::bit\_and::operator() -------------------------- | | | | | --- | --- | --- | | ``` T operator()( const T& lhs, const T& rhs ) const; ``` | | (until C++14) | | ``` constexpr T operator()( const T& lhs, const T& rhs ) const; ``` | | (since C++14) | Returns the result of bitwise AND of `lhs` and `rhs`. ### Parameters | | | | | --- | --- | --- | | lhs, rhs | - | values to compute bitwise AND of | ### Return value The result of `lhs & rhs`. ### Exceptions May throw implementation-defined exceptions. ### Possible implementation | | | --- | | ``` constexpr T operator()(const T &lhs, const T &rhs) const { return lhs & rhs; } ``` | cpp std::greater_equal std::greater\_equal =================== | Defined in header `[<functional>](../../header/functional "cpp/header/functional")` | | | | --- | --- | --- | | ``` template< class T > struct greater_equal; ``` | | (until C++14) | | ``` template< class T = void > struct greater_equal; ``` | | (since C++14) | Function object for performing comparisons. Unless specialized, invokes `operator>=` on type `T`. ### Implementation-defined strict total order over pointers A specialization of `std::greater_equal` for any pointer type yields the implementation-defined strict total order, even if the built-in `>=` operator does not. The implementation-defined strict total order is consistent with the partial order imposed by built-in comparison operators (`<=>`, (since C++20)`<`, `>`, `<=`, and `>=`), and consistent among following standard function objects: * `[std::less](less "cpp/utility/functional/less")`, `[std::greater](greater "cpp/utility/functional/greater")`, `[std::less\_equal](less_equal "cpp/utility/functional/less equal")`, and `std::greater_equal`, when the template argument is a pointer type or `void` (since C++14) | | | | --- | --- | | * [`std::ranges::equal_to`](ranges/equal_to "cpp/utility/functional/ranges/equal to"), [`std::ranges::not_equal_to`](ranges/not_equal_to "cpp/utility/functional/ranges/not equal to"), [`std::ranges::less`](ranges/less "cpp/utility/functional/ranges/less"), [`std::ranges::greater`](ranges/greater "cpp/utility/functional/ranges/greater"), [`std::ranges::less_equal`](ranges/less_equal "cpp/utility/functional/ranges/less equal"), [`std::ranges::greater_equal`](ranges/greater_equal "cpp/utility/functional/ranges/greater equal"), and `[std::compare\_three\_way](../compare/compare_three_way "cpp/utility/compare/compare three way")` | (since C++20) | ### Specializations | | | | --- | --- | | [greater\_equal<void>](greater_equal_void "cpp/utility/functional/greater equal void") (C++14) | function object implementing `x >= y` deducing argument and return types (class template specialization) | ### Member types | Type | Definition | | --- | --- | | `result_type` (deprecated in C++17)(removed in C++20) | `bool` | | `first_argument_type` (deprecated in C++17)(removed in C++20) | `T` | | `second_argument_type` (deprecated in C++17)(removed in C++20) | `T` | | | | | --- | --- | | These member types are obtained via publicly inheriting `[std::binary\_function](http://en.cppreference.com/w/cpp/utility/functional/binary_function)<T, T, bool>`. | (until C++11) | ### Member functions | | | | --- | --- | | operator() | checks if the first argument is *greater* than or *equal* to the second (public member function) | std::greater\_equal::operator() -------------------------------- | | | | | --- | --- | --- | | ``` bool operator()( const T& lhs, const T& rhs ) const; ``` | | (until C++14) | | ``` constexpr bool operator()( const T& lhs, const T& rhs ) const; ``` | | (since C++14) | Checks whether `lhs` is *greater* than or *equal* to `rhs`. ### Parameters | | | | | --- | --- | --- | | lhs, rhs | - | values to compare | ### Return value For `T` which is not a pointer type, `true` if `lhs >= rhs`, `false` otherwise. For `T` which is a pointer type, `true` if `lhs` does not precede `rhs` in the implementation-defined strict total order, `false` otherwise. ### Exceptions May throw implementation-defined exceptions. ### Possible implementation | | | --- | | ``` constexpr bool operator()(const T &lhs, const T &rhs) const { return lhs >= rhs; // assumes that the implementation uses a flat address space } ``` | ### See also | | | | --- | --- | | [less](less "cpp/utility/functional/less") | function object implementing `x < y` (class template) | | [ranges::greater\_equal](ranges/greater_equal "cpp/utility/functional/ranges/greater equal") (C++20) | function object implementing `x >= y` (class) | cpp std::less_equal std::less\_equal ================ | Defined in header `[<functional>](../../header/functional "cpp/header/functional")` | | | | --- | --- | --- | | ``` template< class T > struct less_equal; ``` | | (until C++14) | | ``` template< class T = void > struct less_equal; ``` | | (since C++14) | Function object for performing comparisons. Unless specialized, invokes `operator<=` on type `T`. ### Implementation-defined strict total order over pointers A specialization of `std::less_equal` for any pointer type yields the implementation-defined strict total order, even if the built-in `<=` operator does not. The implementation-defined strict total order is consistent with the partial order imposed by built-in comparison operators (`<=>`, (since C++20)`<`, `>`, `<=`, and `>=`), and consistent among following standard function objects: * `[std::less](less "cpp/utility/functional/less")`, `[std::greater](greater "cpp/utility/functional/greater")`, `std::less_equal`, and `[std::greater\_equal](greater_equal "cpp/utility/functional/greater equal")`, when the template argument is a pointer type or `void` (since C++14) | | | | --- | --- | | * [`std::ranges::equal_to`](ranges/equal_to "cpp/utility/functional/ranges/equal to"), [`std::ranges::not_equal_to`](ranges/not_equal_to "cpp/utility/functional/ranges/not equal to"), [`std::ranges::less`](ranges/less "cpp/utility/functional/ranges/less"), [`std::ranges::greater`](ranges/greater "cpp/utility/functional/ranges/greater"), [`std::ranges::less_equal`](ranges/less_equal "cpp/utility/functional/ranges/less equal"), [`std::ranges::greater_equal`](ranges/greater_equal "cpp/utility/functional/ranges/greater equal"), and `[std::compare\_three\_way](../compare/compare_three_way "cpp/utility/compare/compare three way")` | (since C++20) | ### Specializations | | | | --- | --- | | [less\_equal<void>](less_equal_void "cpp/utility/functional/less equal void") (C++14) | function object implementing `x <= y` deducing argument and return types (class template specialization) | ### Member types | Type | Definition | | --- | --- | | `result_type` (deprecated in C++17)(removed in C++20) | `bool` | | `first_argument_type` (deprecated in C++17)(removed in C++20) | `T` | | `second_argument_type` (deprecated in C++17)(removed in C++20) | `T` | | | | | --- | --- | | These member types are obtained via publicly inheriting `[std::binary\_function](http://en.cppreference.com/w/cpp/utility/functional/binary_function)<T, T, bool>`. | (until C++11) | ### Member functions | | | | --- | --- | | operator() | checks if the first argument is *less* than or *equal* to the second (public member function) | std::less\_equal::operator() ----------------------------- | | | | | --- | --- | --- | | ``` bool operator()( const T& lhs, const T& rhs ) const; ``` | | (until C++14) | | ``` constexpr bool operator()( const T& lhs, const T& rhs ) const; ``` | | (since C++14) | Checks if `lhs` is *less* than or *equal* to `rhs`. ### Parameters | | | | | --- | --- | --- | | lhs, rhs | - | values to compare | ### Return value For `T` which is not a pointer type, `true` if `lhs <= rhs`, `false` otherwise. For `T` which is a pointer type, `true` if `lhs` does not succeed `rhs` in the implementation-defined strict total order, `false` otherwise. ### Exceptions May throw implementation-defined exceptions. ### Possible implementation | | | --- | | ``` constexpr bool operator()(const T &lhs, const T &rhs) const { return lhs <= rhs; // assumes that the implementation uses a flat address space } ``` | ### See also | | | | --- | --- | | [less](less "cpp/utility/functional/less") | function object implementing `x < y` (class template) | | [ranges::less\_equal](ranges/less_equal "cpp/utility/functional/ranges/less equal") (C++20) | function object implementing `x <= y` (class) | cpp std::plus std::plus ========= | Defined in header `[<functional>](../../header/functional "cpp/header/functional")` | | | | --- | --- | --- | | ``` template< class T > struct plus; ``` | | (until C++14) | | ``` template< class T = void > struct plus; ``` | | (since C++14) | Function object for performing addition. Effectively calls `operator+` on two instances of type `T`. ### Specializations | | | | | | --- | --- | --- | --- | | The standard library provides a specialization of `std::plus` when `T` is not specified, which leaves the parameter types and return type to be deduced. | | | | --- | --- | | [plus<void>](plus_void "cpp/utility/functional/plus void") (C++14) | function object implementing `x + y` deducing argument and return types (class template specialization) | | (since C++14) | ### Member types | Type | Definition | | --- | --- | | `result_type` (deprecated in C++17)(removed in C++20) | `T` | | `first_argument_type` (deprecated in C++17)(removed in C++20) | `T` | | `second_argument_type` (deprecated in C++17)(removed in C++20) | `T` | | | | | --- | --- | | These member types are obtained via publicly inheriting `[std::binary\_function](http://en.cppreference.com/w/cpp/utility/functional/binary_function)<T, T, T>`. | (until C++11) | ### Member functions | | | | --- | --- | | **operator()** | returns the sum of two arguments (public member function) | std::plus::operator() ---------------------- | | | | | --- | --- | --- | | ``` T operator()( const T& lhs, const T& rhs ) const; ``` | | (until C++14) | | ``` constexpr T operator()( const T& lhs, const T& rhs ) const; ``` | | (since C++14) | Returns the sum of `lhs` and `rhs`. ### Parameters | | | | | --- | --- | --- | | lhs, rhs | - | values to sum | ### Return value The result of `lhs + rhs`. ### Exceptions May throw implementation-defined exceptions. ### Possible implementation | | | --- | | ``` constexpr T operator()(const T &lhs, const T &rhs) const { return lhs + rhs; } ``` | cpp std::bit_or std::bit\_or ============ | Defined in header `[<functional>](../../header/functional "cpp/header/functional")` | | | | --- | --- | --- | | ``` template< class T > struct bit_or; ``` | | (until C++14) | | ``` template< class T = void > struct bit_or; ``` | | (since C++14) | Function object for performing bitwise OR. Effectively calls `operator|` on type `T`. ### Specializations | | | | | | --- | --- | --- | --- | | The standard library provides a specialization of `std::bit_or` when `T` is not specified, which leaves the parameter types and return type to be deduced. | | | | --- | --- | | [bit\_or<void>](bit_or_void "cpp/utility/functional/bit or void") (C++14) | function object implementing `x | y` deducing argument and return types (class template specialization) | | (since C++14) | ### Member types | Type | Definition | | --- | --- | | `result_type` (deprecated in C++17)(removed in C++20) | `T` | | `first_argument_type` (deprecated in C++17)(removed in C++20) | `T` | | `second_argument_type` (deprecated in C++17)(removed in C++20) | `T` | | | | | --- | --- | | These member types are obtained via publicly inheriting `[std::binary\_function](http://en.cppreference.com/w/cpp/utility/functional/binary_function)<T, T, T>`. | (until C++11) | ### Member functions | | | | --- | --- | | operator() | returns the result of bitwise OR of two arguments (public member function) | std::bit\_or::operator() ------------------------- | | | | | --- | --- | --- | | ``` T operator()( const T& lhs, const T& rhs ) const; ``` | | (until C++14) | | ``` constexpr T operator()( const T& lhs, const T& rhs ) const; ``` | | (since C++14) | Returns the result of bitwise OR of `lhs` and `rhs`. ### Parameters | | | | | --- | --- | --- | | lhs, rhs | - | values to compute bitwise OR of | ### Return value The result of `lhs | rhs`. ### Exceptions May throw implementation-defined exceptions. ### Possible implementation | | | --- | | ``` constexpr T operator()(const T &lhs, const T &rhs) const { return lhs | rhs; } ``` | cpp std::bit_xor std::bit\_xor ============= | Defined in header `[<functional>](../../header/functional "cpp/header/functional")` | | | | --- | --- | --- | | ``` template< class T > struct bit_xor; ``` | | (until C++14) | | ``` template< class T = void > struct bit_xor; ``` | | (since C++14) | Function object for performing bitwise XOR. Effectively calls `operator^` on type `T`. ### Specializations | | | | | | --- | --- | --- | --- | | The standard library provides a specialization of `std::bit_xor` when `T` is not specified, which leaves the parameter types and return type to be deduced. | | | | --- | --- | | [bit\_xor<void>](bit_xor_void "cpp/utility/functional/bit xor void") (C++14) | function object implementing `x ^ y` deducing argument and return types (class template specialization) | | (since C++14) | ### Member types | Type | Definition | | --- | --- | | `result_type` (deprecated in C++17)(removed in C++20) | `T` | | `first_argument_type` (deprecated in C++17)(removed in C++20) | `T` | | `second_argument_type` (deprecated in C++17)(removed in C++20) | `T` | | | | | --- | --- | | These member types are obtained via publicly inheriting `[std::binary\_function](http://en.cppreference.com/w/cpp/utility/functional/binary_function)<T, T, T>`. | (until C++11) | ### Member functions | | | | --- | --- | | operator() | returns the result of bitwise XOR of two arguments (public member function) | std::bit\_xor::operator() -------------------------- | | | | | --- | --- | --- | | ``` T operator()( const T& lhs, const T& rhs ) const; ``` | | (until C++14) | | ``` constexpr T operator()( const T& lhs, const T& rhs ) const; ``` | | (since C++14) | Returns the result of bitwise XOR of `lhs` and `rhs`. ### Parameters | | | | | --- | --- | --- | | lhs, rhs | - | values to compute bitwise XOR of | ### Return value The result of `lhs ^ rhs`. ### Exceptions May throw implementation-defined exceptions. ### Possible implementation | | | --- | | ``` constexpr T operator()(const T &lhs, const T &rhs) const { return lhs ^ rhs; } ``` | cpp std::boyer_moore_searcher std::boyer\_moore\_searcher =========================== | Defined in header `[<functional>](../../header/functional "cpp/header/functional")` | | | | --- | --- | --- | | ``` template< class RandomIt1, class Hash = std::hash<typename std::iterator_traits<RandomIt1>::value_type>, class BinaryPredicate = std::equal_to<> > class boyer_moore_searcher; ``` | | (since C++17) | A searcher suitable for use with the [Searcher](https://en.cppreference.com/mwiki/index.php?title=cpp/named_req/Searcher&action=edit&redlink=1 "cpp/named req/Searcher (page does not exist)") overload of `[std::search](../../algorithm/search "cpp/algorithm/search")` that implements the [Boyer-Moore string searching algorithm](https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_string_search_algorithm "enwiki:Boyer–Moore string search algorithm"). `boyer_moore_searcher` is [CopyConstructible](../../named_req/copyconstructible "cpp/named req/CopyConstructible") and [CopyAssignable](../../named_req/copyassignable "cpp/named req/CopyAssignable"). `RandomIt1` must meet the requirements of [LegacyRandomAccessIterator](../../named_req/randomaccessiterator "cpp/named req/RandomAccessIterator"). ### Member functions std::boyer\_moore\_searcher::boyer\_moore\_searcher ---------------------------------------------------- | | | | | --- | --- | --- | | ``` boyer_moore_searcher( RandomIt1 pat_first, RandomIt1 pat_last, Hash hf = Hash(), BinaryPredicate pred = BinaryPredicate()); ``` | | | Constructs a `boyer_moore_searcher` by storing copies of `pat_first`, `pat_last`, `hf`, and `pred`, setting up any necessary internal data structures. The value type of `RandomIt1` must be [DefaultConstructible](../../named_req/defaultconstructible "cpp/named req/DefaultConstructible"), [CopyConstructible](../../named_req/copyconstructible "cpp/named req/CopyConstructible") and [CopyAssignable](../../named_req/copyassignable "cpp/named req/CopyAssignable"). For any two values `A` and `B` of the type `[std::iterator\_traits](http://en.cppreference.com/w/cpp/iterator/iterator_traits)<RandomIt1>::value\_type`, if `pred(A, B) == true`, then `hf(A) == hf(B)` shall be `true`. ### Parameters | | | | | --- | --- | --- | | pat\_first, pat\_last | - | a pair of iterators designating the string to be searched for | | hf | - | a callable object used to hash the elements of the string | | pred | - | a callable object used to determine equality | ### Exceptions Any exceptions thrown by. * the copy constructor of `RandomIt1`; * the default constructor, copy constructor, and copy assignment operator of the value type of `RandomIt1`; or * the copy constructor and function call operator of `BinaryPredicate` or `Hash`. May also throw `[std::bad\_alloc](../../memory/new/bad_alloc "cpp/memory/new/bad alloc")` if additional memory required for internal data structures cannot be allocated. std::boyer\_moore\_searcher::operator() ---------------------------------------- | | | | | --- | --- | --- | | ``` template< class RandomIt2 > std::pair<RandomIt2,RandomIt2> operator()( RandomIt2 first, RandomIt2 last ) const; ``` | | (since C++17) | The member function called by the Searcher overload of `[std::search](../../algorithm/search "cpp/algorithm/search")` to perform a search with this searcher. `RandomIt2` must meet the requirements of [LegacyRandomAccessIterator](../../named_req/randomaccessiterator "cpp/named req/RandomAccessIterator"). `RandomIt1` and `RandomIt2` must have the same value type. ### Parameters | | | | | --- | --- | --- | | first, last | - | a pair of iterators designating the string to be examined | ### Return value If the pattern ([pat\_first, pat\_last)) is empty, returns `[std::make\_pair](http://en.cppreference.com/w/cpp/utility/pair/make_pair)(first, first)`. Otherwise, returns a pair of iterators to the first and one past last positions in [first, last) where a subsequence that compares equal to [pat\_first, pat\_last) as defined by `pred` is located, or `[std::make\_pair](http://en.cppreference.com/w/cpp/utility/pair/make_pair)(last, last)` otherwise. ### Notes | [Feature-test](../feature_test "cpp/utility/feature test") macro | | --- | | [`__cpp_lib_boyer_moore_searcher`](../../feature_test#Library_features "cpp/feature test") | ### Example ``` #include <iomanip> #include <iostream> #include <algorithm> #include <functional> #include <string_view> int main() { constexpr std::string_view haystack = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed " "do eiusmod tempor incididunt ut labore et dolore magna aliqua"; const std::string_view needle {"pisci"}; if (const auto it = std::search(haystack.begin(), haystack.end(), std::boyer_moore_searcher(needle.begin(), needle.end())); it != haystack.end() ) { std::cout << "The string " << quoted(needle) << " found at offset " << it - haystack.begin() << '\n'; } else { std::cout << "The string " << std::quoted(needle) << " not found\n"; } } ``` Output: ``` The string "pisci" found at offset 43 ``` ### See also | | | | --- | --- | | [search](../../algorithm/search "cpp/algorithm/search") | searches for a range of elements (function template) | | [default\_searcher](default_searcher "cpp/utility/functional/default searcher") (C++17) | standard C++ library search algorithm implementation (class template) | | [boyer\_moore\_horspool\_searcher](boyer_moore_horspool_searcher "cpp/utility/functional/boyer moore horspool searcher") (C++17) | Boyer-Moore-Horspool search algorithm implementation (class template) |
programming_docs
cpp std::function std::function ============= | Defined in header `[<functional>](../../header/functional "cpp/header/functional")` | | | | --- | --- | --- | | ``` template< class > class function; /* undefined */ ``` | | (since C++11) | | ``` template< class R, class... Args > class function<R(Args...)>; ``` | | (since C++11) | Class template `std::function` is a general-purpose polymorphic function wrapper. Instances of `std::function` can store, copy, and invoke any [CopyConstructible](../../named_req/copyconstructible "cpp/named req/CopyConstructible") [Callable](../../named_req/callable "cpp/named req/Callable") *target* -- functions, [lambda expressions](../../language/lambda "cpp/language/lambda"), [bind expressions](bind "cpp/utility/functional/bind"), or other function objects, as well as pointers to member functions and pointers to data members. The stored callable object is called the *target* of `std::function`. If a `std::function` contains no target, it is called *empty*. Invoking the *target* of an *empty* `std::function` results in `[std::bad\_function\_call](bad_function_call "cpp/utility/functional/bad function call")` exception being thrown. `std::function` satisfies the requirements of [CopyConstructible](../../named_req/copyconstructible "cpp/named req/CopyConstructible") and [CopyAssignable](../../named_req/copyassignable "cpp/named req/CopyAssignable"). ### Member types | Type | Definition | | --- | --- | | `result_type` | `R` | | `argument_type`(deprecated in C++17)(removed in C++20) | `T` if `sizeof...(Args)==1` and `T` is the first and only type in `Args...` | | `first_argument_type`(deprecated in C++17)(removed in C++20) | `T1` if `sizeof...(Args)==2` and `T1` is the first of the two types in `Args...` | | `second_argument_type`(deprecated in C++17)(removed in C++20) | `T2` if `sizeof...(Args)==2` and `T2` is the second of the two types in `Args...` | ### Member functions | | | | --- | --- | | [(constructor)](function/function "cpp/utility/functional/function/function") | constructs a new `std::function` instance (public member function) | | [(destructor)](function/~function "cpp/utility/functional/function/~function") | destroys a `std::function` instance (public member function) | | [operator=](function/operator= "cpp/utility/functional/function/operator=") | assigns a new target (public member function) | | [swap](function/swap "cpp/utility/functional/function/swap") | swaps the contents (public member function) | | [assign](function/assign "cpp/utility/functional/function/assign") (removed in C++17) | assigns a new target (public member function) | | [operator bool](function/operator_bool "cpp/utility/functional/function/operator bool") | checks if a target is contained (public member function) | | [operator()](function/operator() "cpp/utility/functional/function/operator()") | invokes the target (public member function) | | Target access | | [target\_type](function/target_type "cpp/utility/functional/function/target type") | obtains the `typeid` of the stored target (public member function) | | [target](function/target "cpp/utility/functional/function/target") | obtains a pointer to the stored target (public member function) | ### Non-member functions | | | | --- | --- | | [std::swap(std::function)](function/swap2 "cpp/utility/functional/function/swap2") (C++11) | specializes the `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | | [operator==operator!=](function/operator_cmp "cpp/utility/functional/function/operator cmp") (removed in C++20) | compares a `std::function` with `nullptr` (function template) | ### Helper classes | | | | --- | --- | | [std::uses\_allocator<std::function>](function/uses_allocator "cpp/utility/functional/function/uses allocator") (C++11) (until C++17) | specializes the `[std::uses\_allocator](../../memory/uses_allocator "cpp/memory/uses allocator")` type trait (class template specialization) | ### [Deduction guides](function/deduction_guides "cpp/utility/functional/function/deduction guides")(since C++17) ### Notes | | | | --- | --- | | Care should be taken when a `std::function`, whose result type is a reference, is initialized from a lambda expression without a trailing-return-type. Due to the way auto deduction works, such lambda expression will always return a prvalue. Hence, the resulting reference will usually bind to a temporary whose lifetime ends when [`std::function::operator()`](function/operator() "cpp/utility/functional/function/operator()") returns. | (until C++23) | | If a `std::function` returning a reference is initialized from a function or function object returning a prvalue (including a lambda expression without a trailing-return-type), the program is ill-formed because binding the returned referenced to a temporary object is forbidden. | (since C++23) | ``` std::function<const int&()> F([]{ return 42; }); // Error since C++23: can't bind // the returned reference to a temporary int x = F(); // Undefined behavior until C++23: the result of F() is a dangling reference std::function<int&()> G([]()->int& { static int i{0x2A}; return i; }); // OK std::function<const int&()> H([i{052}]->const int& { return i; }); // OK ``` ### Example ``` #include <functional> #include <iostream> struct Foo { Foo(int num) : num_(num) {} void print_add(int i) const { std::cout << num_+i << '\n'; } int num_; }; void print_num(int i) { std::cout << i << '\n'; } struct PrintNum { void operator()(int i) const { std::cout << i << '\n'; } }; int main() { // store a free function std::function<void(int)> f_display = print_num; f_display(-9); // store a lambda std::function<void()> f_display_42 = []() { print_num(42); }; f_display_42(); // store the result of a call to std::bind std::function<void()> f_display_31337 = std::bind(print_num, 31337); f_display_31337(); // store a call to a member function std::function<void(const Foo&, int)> f_add_display = &Foo::print_add; const Foo foo(314159); f_add_display(foo, 1); f_add_display(314159, 1); // store a call to a data member accessor std::function<int(Foo const&)> f_num = &Foo::num_; std::cout << "num_: " << f_num(foo) << '\n'; // store a call to a member function and object using std::placeholders::_1; std::function<void(int)> f_add_display2 = std::bind( &Foo::print_add, foo, _1 ); f_add_display2(2); // store a call to a member function and object ptr std::function<void(int)> f_add_display3 = std::bind( &Foo::print_add, &foo, _1 ); f_add_display3(3); // store a call to a function object std::function<void(int)> f_display_obj = PrintNum(); f_display_obj(18); auto factorial = [](int n) { // store a lambda object to emulate "recursive lambda"; aware of extra overhead std::function<int(int)> fac = [&](int n){ return (n < 2) ? 1 : n*fac(n-1); }; // note that "auto fac = [&](int n){...};" does not work in recursive calls return fac(n); }; for (int i{5}; i != 8; ++i) { std::cout << i << "! = " << factorial(i) << "; "; } } ``` Possible output: ``` -9 42 31337 314160 314160 num_: 314159 314161 314162 18 5! = 120; 6! = 720; 7! = 5040; ``` ### See also | | | | --- | --- | | [move\_only\_function](move_only_function "cpp/utility/functional/move only function") (C++23) | wraps callable object of any type with specified function call signature (class template) | | [bad\_function\_call](bad_function_call "cpp/utility/functional/bad function call") (C++11) | the exception thrown when invoking an empty `std::function` (class) | | [mem\_fn](mem_fn "cpp/utility/functional/mem fn") (C++11) | creates a function object out of a pointer to a member (function template) | cpp std::not_fn std::not\_fn ============ | Defined in header `[<functional>](../../header/functional "cpp/header/functional")` | | | | --- | --- | --- | | ``` template< class F> /*unspecified*/ not_fn( F&& f ); ``` | | (since C++17) (until C++20) | | ``` template< class F> constexpr /*unspecified*/ not_fn( F&& f ); ``` | | (since C++20) | Creates a forwarding call wrapper that returns the negation of the callable object it holds. ### Parameters | | | | | --- | --- | --- | | f | - | the object from which the [Callable](../../named_req/callable "cpp/named req/Callable") object held by the wrapper is constructed | | Type requirements | | -`[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<F>` must meet the requirements of [Callable](../../named_req/callable "cpp/named req/Callable") and [MoveConstructible](../../named_req/moveconstructible "cpp/named req/MoveConstructible"). | | -`[std::is\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_constructible)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<F>, F>` is required to be true | ### Return value A function object of unspecified type T. It has the following members: std::not\_fn *return type* --------------------------- #### Member objects The return type of `std::not_fn` holds a member object of type `[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<F>`. #### Constructors | | | | | --- | --- | --- | | | (1) | | | ``` explicit T(F&& f); // exposition only ``` | (since C++17) (until C++20) | | ``` explicit constexpr T(F&& f); // exposition only ``` | (since C++20) | | ``` T(T&& f) = default; T(const T& f) = default; ``` | (2) | | 1) The constructor direct-non-list-initializes the member object (of type `[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<F>`) from `[std::forward](http://en.cppreference.com/w/cpp/utility/forward)<F>(f)`. Throws any exception thrown by the constructor selected 2) Because `[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<F>` is required to be [MoveConstructible](../../named_req/moveconstructible "cpp/named req/MoveConstructible"), the returned call wrapper is always [MoveConstructible](../../named_req/moveconstructible "cpp/named req/MoveConstructible"), and is [CopyConstructible](../../named_req/copyconstructible "cpp/named req/CopyConstructible") if `[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<F>` is [CopyConstructible](../../named_req/copyconstructible "cpp/named req/CopyConstructible"). #### Member function `operator()` | | | | | --- | --- | --- | | | (1) | | | ``` template<class... Args> auto operator()(Args&&... args) & -> decltype( !std::declval<std::invoke_result_t<std::decay_t<F>&, Args...>>()); template<class... Args> auto operator()(Args&&... args) const& -> decltype( !std::declval<std::invoke_result_t<std::decay_t<F> const&, Args...>>()); ``` | (since C++17) (until C++20) | | ``` template<class... Args> constexpr auto operator()(Args&&... args) & noexcept(/*see below*/) -> decltype( !std::declval<std::invoke_result_t<std::decay_t<F>&, Args...>>()); template<class... Args> constexpr auto operator()(Args&&... args) const& noexcept(/*see below*/) -> decltype( !std::declval<std::invoke_result_t<std::decay_t<F> const&, Args...>>()); ``` | (since C++20) | | | (2) | | | ``` template<class... Args> auto operator()(Args&&... args) && -> decltype( !std::declval<std::invoke_result_t<std::decay_t<F>, Args...>>()); template<class... Args> auto operator()(Args&&... args) const&& -> decltype( !std::declval<std::invoke_result_t<std::decay_t<F> const, Args...>>()); ``` | (since C++17) (until C++20) | | ``` template<class... Args> constexpr auto operator()(Args&&... args) && noexcept(/*see below*/) -> decltype( !std::declval<std::invoke_result_t<std::decay_t<F>, Args...>>()); template<class... Args> constexpr auto operator()(Args&&... args) const&& noexcept(/*see below*/) -> decltype( !std::declval<std::invoke_result_t<std::decay_t<F> const, Args...>>()); ``` | (since C++20) | | | | | --- | --- | | 1) Equivalent to `return ![std::invoke](http://en.cppreference.com/w/cpp/utility/functional/invoke)(fd, [std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Args>(args)...);` 2) Equivalent to `return ![std::invoke](http://en.cppreference.com/w/cpp/utility/functional/invoke)(std::move(fd), [std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Args>(args)...);` | (since C++17)(until C++20) | | 1) Expression-equivalent to `![std::invoke](http://en.cppreference.com/w/cpp/utility/functional/invoke)(fd, [std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Args>(args)...)` 2) Expression-equivalent to `![std::invoke](http://en.cppreference.com/w/cpp/utility/functional/invoke)(std::move(fd), [std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Args>(args)...)` | (since C++20) | where `fd` is the member object of type `[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<F>` ### Expression-equivalent Expression `e` is *expression-equivalent* to expression `f`, if. * `e` and `f` have the same effects, and * either both are [constant subexpressions](../../language/constant_expression "cpp/language/constant expression") or else neither is a constant subexpression, and * either both are [potentially-throwing](../../language/noexcept_spec "cpp/language/noexcept spec") or else neither is potentially-throwing (i.e. `noexcept(e) == noexcept(f)`). ### Exceptions Throws no exceptions, unless the construction of `fd` throws. ### Possible implementation | | | --- | | ``` namespace detail { template<class F> struct not_fn_t { F f; template<class... Args> constexpr auto operator()(Args&&... args) & noexcept(noexcept(!std::invoke(f, std::forward<Args>(args)...))) -> decltype(!std::invoke(f, std::forward<Args>(args)...)) { return !std::invoke(f, std::forward<Args>(args)...); } template<class... Args> constexpr auto operator()(Args&&... args) const& noexcept(noexcept(!std::invoke(f, std::forward<Args>(args)...))) -> decltype(!std::invoke(f, std::forward<Args>(args)...)) { return !std::invoke(f, std::forward<Args>(args)...); } template<class... Args> constexpr auto operator()(Args&&... args) && noexcept(noexcept(!std::invoke(std::move(f), std::forward<Args>(args)...))) -> decltype(!std::invoke(std::move(f), std::forward<Args>(args)...)) { return !std::invoke(std::move(f), std::forward<Args>(args)...); } template<class... Args> constexpr auto operator()(Args&&... args) const&& noexcept(noexcept(!std::invoke(std::move(f), std::forward<Args>(args)...))) -> decltype(!std::invoke(std::move(f), std::forward<Args>(args)...)) { return !std::invoke(std::move(f), std::forward<Args>(args)...); } }; } template<class F> constexpr detail::not_fn_t<std::decay_t<F>> not_fn(F&& f) { return { std::forward<F>(f) }; } ``` | ### Notes `not_fn` is intended to replace the C++03-era negators `[std::not1](not1 "cpp/utility/functional/not1")` and `[std::not2](not2 "cpp/utility/functional/not2")`. | [Feature-test](../feature_test "cpp/utility/feature test") macro | | --- | | [`__cpp_lib_not_fn`](../../feature_test#Library_features "cpp/feature test") | ### Example ### See also | | | | --- | --- | | [not1](not1 "cpp/utility/functional/not1") (deprecated in C++17)(removed in C++20) | constructs custom `[std::unary\_negate](unary_negate "cpp/utility/functional/unary negate")` object (function template) | | [not2](not2 "cpp/utility/functional/not2") (deprecated in C++17)(removed in C++20) | constructs custom `[std::binary\_negate](binary_negate "cpp/utility/functional/binary negate")` object (function template) | cpp std::multiplies std::multiplies =============== | Defined in header `[<functional>](../../header/functional "cpp/header/functional")` | | | | --- | --- | --- | | ``` template< class T > struct multiplies; ``` | | (until C++14) | | ``` template< class T = void > struct multiplies; ``` | | (since C++14) | Function object for performing multiplication. Effectively calls `operator*` on two instances of type `T`. ### Specializations | | | | | | --- | --- | --- | --- | | The standard library provides a specialization of `std::multiplies` when `T` is not specified, which leaves the parameter types and return type to be deduced. | | | | --- | --- | | [multiplies<void>](multiplies_void "cpp/utility/functional/multiplies void") (C++14) | function object implementing `x * y` deducing argument and return types (class template specialization) | | (since C++14) | ### Member types | Type | Definition | | --- | --- | | `result_type` (deprecated in C++17)(removed in C++20) | `T` | | `first_argument_type` (deprecated in C++17)(removed in C++20) | `T` | | `second_argument_type` (deprecated in C++17)(removed in C++20) | `T` | | | | | --- | --- | | These member types are obtained via publicly inheriting `[std::binary\_function](http://en.cppreference.com/w/cpp/utility/functional/binary_function)<T, T, T>`. | (until C++11) | ### Member functions | | | | --- | --- | | operator() | returns the product of two arguments (public member function) | std::multiplies::operator() ---------------------------- | | | | | --- | --- | --- | | ``` T operator()( const T& lhs, const T& rhs ) const; ``` | | (until C++14) | | ``` constexpr T operator()( const T& lhs, const T& rhs ) const; ``` | | (since C++14) | Returns the product of `lhs` and `rhs`. ### Parameters | | | | | --- | --- | --- | | lhs, rhs | - | values to multiply | ### Return value The result of `lhs * rhs`. ### Exceptions May throw implementation-defined exceptions. ### Possible implementation | | | --- | | ``` constexpr T operator()(const T &lhs, const T &rhs) const { return lhs * rhs; } ``` | cpp std::default_searcher std::default\_searcher ====================== | Defined in header `[<functional>](../../header/functional "cpp/header/functional")` | | | | --- | --- | --- | | ``` template< class ForwardIt, class BinaryPredicate = std::equal_to<> > class default_searcher; ``` | | (since C++17) | A class suitable for use with [Searcher](https://en.cppreference.com/mwiki/index.php?title=cpp/named_req/Searcher&action=edit&redlink=1 "cpp/named req/Searcher (page does not exist)") overload of `[std::search](../../algorithm/search "cpp/algorithm/search")` that delegates the search operation to the pre-C++17 standard library's `[std::search](../../algorithm/search "cpp/algorithm/search")`. `default_searcher` is [CopyConstructible](../../named_req/copyconstructible "cpp/named req/CopyConstructible") and [CopyAssignable](../../named_req/copyassignable "cpp/named req/CopyAssignable"). ### Member functions std::default\_searcher::default\_searcher ------------------------------------------ | | | | | --- | --- | --- | | ``` default_searcher( ForwardIt pat_first, ForwardIt pat_last, BinaryPredicate pred = BinaryPredicate()); ``` | | (since C++17) (until C++20) | | ``` constexpr default_searcher( ForwardIt pat_first, ForwardIt pat_last, BinaryPredicate pred = BinaryPredicate()); ``` | | (since C++20) | Constructs a `default_searcher` by storing copies of `pat_first`, `pat_last`, and `pred`. ### Parameters | | | | | --- | --- | --- | | pat\_first, pat\_last | - | a pair of iterators designating the string to be searched for | | pred | - | a callable object used to determine equality | ### Exceptions Any exceptions thrown by the copy constructors of `BinaryPredicate` or `ForwardIt`. std::default\_searcher::operator() ----------------------------------- | | | | | --- | --- | --- | | ``` template< class ForwardIt2 > std::pair<ForwardIt2, ForwardIt2> operator()( ForwardIt2 first, ForwardIt2 last ) const; ``` | | (since C++17) (until C++20) | | ``` template< class ForwardIt2 > constexpr std::pair<ForwardIt2, ForwardIt2> operator()( ForwardIt2 first, ForwardIt2 last ) const; ``` | | (since C++20) | The member function called by the Searcher overload of `[std::search](../../algorithm/search "cpp/algorithm/search")` to perform a search with this searcher. Returns a pair of iterators `i, j`, where `i` is `[std::search](http://en.cppreference.com/w/cpp/algorithm/search)(first, last, pat_first, pat_last, pred)` and `j` is `[std::next](http://en.cppreference.com/w/cpp/iterator/next)(i, [std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(pat_first, pat_last))` unless `std::search` returned `last` (no match), in which case `j` equals `last` as well. ### Parameters | | | | | --- | --- | --- | | first, last | - | a pair of iterators designating the string to be examined | ### Return value A pair of iterators to the first and one past last positions in [first, last) where a subsequence that compares equal to [pat\_first, pat\_last) as defined by `pred` is located, or a pair of copies of `last` otherwise. ### Example ``` #include <iostream> #include <string> #include <algorithm> #include <functional> int main() { std::string in = "Lorem ipsum dolor sit amet, consectetur adipiscing elit," " sed do eiusmod tempor incididunt ut labore et dolore magna aliqua"; std::string needle = "pisci"; auto it = std::search(in.begin(), in.end(), std::default_searcher( needle.begin(), needle.end())); if(it != in.end()) std::cout << "The string " << needle << " found at offset " << it - in.begin() << '\n'; else std::cout << "The string " << needle << " not found\n"; } ``` Output: ``` The string pisci found at offset 43 ``` ### See also | | | | --- | --- | | [search](../../algorithm/search "cpp/algorithm/search") | searches for a range of elements (function template) | | [boyer\_moore\_searcher](boyer_moore_searcher "cpp/utility/functional/boyer moore searcher") (C++17) | Boyer-Moore search algorithm implementation (class template) | | [boyer\_moore\_horspool\_searcher](boyer_moore_horspool_searcher "cpp/utility/functional/boyer moore horspool searcher") (C++17) | Boyer-Moore-Horspool search algorithm implementation (class template) |
programming_docs
cpp std::logical_and std::logical\_and ================= | Defined in header `[<functional>](../../header/functional "cpp/header/functional")` | | | | --- | --- | --- | | ``` template< class T > struct logical_and; ``` | | (until C++14) | | ``` template< class T = void > struct logical_and; ``` | | (since C++14) | Function object for performing logical AND (logical conjunction). Effectively calls `operator&&` on type `T`. ### Specializations | | | | | | --- | --- | --- | --- | | The standard library provides a specialization of `std::logical_and` when `T` is not specified, which leaves the parameter types and return type to be deduced. | | | | --- | --- | | [logical\_and<void>](logical_and_void "cpp/utility/functional/logical and void") (C++14) | function object implementing `x && y` deducing argument and return types (class template specialization) | | (since C++14) | ### Member types | Type | Definition | | --- | --- | | `result_type` (deprecated in C++17)(removed in C++20) | `bool` | | `first_argument_type` (deprecated in C++17)(removed in C++20) | `T` | | `second_argument_type` (deprecated in C++17)(removed in C++20) | `T` | | | | | --- | --- | | These member types are obtained via publicly inheriting `[std::binary\_function](http://en.cppreference.com/w/cpp/utility/functional/binary_function)<T, T, bool>`. | (until C++11) | ### Member functions | | | | --- | --- | | operator() | returns the logical AND of the two arguments (public member function) | std::logical\_and::operator() ------------------------------ | | | | | --- | --- | --- | | ``` bool operator()( const T& lhs, const T& rhs ) const; ``` | | (until C++14) | | ``` constexpr bool operator()( const T& lhs, const T& rhs ) const; ``` | | (since C++14) | Returns the logical AND of `lhs` and `rhs`. ### Parameters | | | | | --- | --- | --- | | lhs, rhs | - | values to compute logical AND of | ### Return value The result of `lhs && rhs`. ### Exceptions May throw implementation-defined exceptions. ### Possible implementation | | | --- | | ``` constexpr bool operator()(const T &lhs, const T &rhs) const { return lhs && rhs; } ``` | cpp std::logical_or std::logical\_or ================ | Defined in header `[<functional>](../../header/functional "cpp/header/functional")` | | | | --- | --- | --- | | ``` template< class T > struct logical_or; ``` | | (until C++14) | | ``` template< class T = void > struct logical_or; ``` | | (since C++14) | Function object for performing logical OR (logical disjunction). Effectively calls `operator||` on type `T`. ### Specializations | | | | | | --- | --- | --- | --- | | The standard library provides a specialization of `std::logical_or` when `T` is not specified, which leaves the parameter types and return type to be deduced. | | | | --- | --- | | [logical\_or<void>](logical_or_void "cpp/utility/functional/logical or void") (C++14) | function object implementing `x || y` deducing argument and return types (class template specialization) | | (since C++14) | ### Member types | Type | Definition | | --- | --- | | `result_type` (deprecated in C++17)(removed in C++20) | `bool` | | `first_argument_type` (deprecated in C++17)(removed in C++20) | `T` | | `second_argument_type` (deprecated in C++17)(removed in C++20) | `T` | | | | | --- | --- | | These member types are obtained via publicly inheriting `[std::binary\_function](http://en.cppreference.com/w/cpp/utility/functional/binary_function)<T, T, bool>`. | (until C++11) | ### Member functions | | | | --- | --- | | operator() | returns the logical OR of the two arguments (public member function) | std::logical\_or::operator() ----------------------------- | | | | | --- | --- | --- | | ``` bool operator()( const T& lhs, const T& rhs ) const; ``` | | (until C++14) | | ``` constexpr bool operator()( const T& lhs, const T& rhs ) const; ``` | | (since C++14) | Returns the logical OR of `lhs` and `rhs`. ### Parameters | | | | | --- | --- | --- | | lhs, rhs | - | values to compute logical OR of | ### Return value The result of `lhs || rhs`. ### Exceptions May throw implementation-defined exceptions. ### Possible implementation | | | --- | | ``` constexpr bool operator()(const T &lhs, const T &rhs) const { return lhs || rhs; } ``` | cpp std::boyer_moore_horspool_searcher std::boyer\_moore\_horspool\_searcher ===================================== | Defined in header `[<functional>](../../header/functional "cpp/header/functional")` | | | | --- | --- | --- | | ``` template< class RandomIt1, class Hash = std::hash<typename std::iterator_traits<RandomIt1>::value_type>, class BinaryPredicate = std::equal_to<> > class boyer_moore_horspool_searcher; ``` | | (since C++17) | A searcher suitable for use with the [Searcher](https://en.cppreference.com/mwiki/index.php?title=cpp/named_req/Searcher&action=edit&redlink=1 "cpp/named req/Searcher (page does not exist)") overload of `[std::search](../../algorithm/search "cpp/algorithm/search")` that implements the [Boyer-Moore-Horspool string searching algorithm](https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore%E2%80%93Horspool_algorithm "enwiki:Boyer–Moore–Horspool algorithm"). `boyer_moore_horspool_searcher` is [CopyConstructible](../../named_req/copyconstructible "cpp/named req/CopyConstructible") and [CopyAssignable](../../named_req/copyassignable "cpp/named req/CopyAssignable"). `RandomIt1` must meet the requirements of [LegacyRandomAccessIterator](../../named_req/randomaccessiterator "cpp/named req/RandomAccessIterator"). ### Member functions std::boyer\_moore\_horspool\_searcher::boyer\_moore\_horspool\_searcher ------------------------------------------------------------------------ | | | | | --- | --- | --- | | ``` boyer_moore_horspool_searcher( RandomIt1 pat_first, RandomIt1 pat_last, Hash hf = Hash(), BinaryPredicate pred = BinaryPredicate()); ``` | | | Constructs a `boyer_moore_horspool_searcher` by storing copies of `pat_first`, `pat_last`, `hf`, and `pred`, setting up any necessary internal data structures. The value type of `RandomIt1` must be [DefaultConstructible](../../named_req/defaultconstructible "cpp/named req/DefaultConstructible"), [CopyConstructible](../../named_req/copyconstructible "cpp/named req/CopyConstructible") and [CopyAssignable](../../named_req/copyassignable "cpp/named req/CopyAssignable"). For any two values `A` and `B` of the type `[std::iterator\_traits](http://en.cppreference.com/w/cpp/iterator/iterator_traits)<RandomIt1>::value\_type`, if `pred(A, B) == true`, then `hf(A) == hf(B)` shall be `true`. ### Parameters | | | | | --- | --- | --- | | pat\_first, pat\_last | - | a pair of iterators designating the string to be searched for | | hf | - | a callable object used to hash the elements of the string | | pred | - | a callable object used to determine equality | ### Exceptions Any exceptions thrown by. * the copy constructor of `RandomIt1`; * the default constructor, copy constructor, or copy assignment operator of the value type of `RandomIt1`; or * the copy constructor or function call operator of `BinaryPredicate` or `Hash`. May also throw `[std::bad\_alloc](../../memory/new/bad_alloc "cpp/memory/new/bad alloc")` if additional memory required for internal data structures cannot be allocated. std::boyer\_moore\_horspool\_searcher::operator() -------------------------------------------------- | | | | | --- | --- | --- | | ``` template< class RandomIt2 > std::pair<RandomIt2,RandomIt2> operator()( RandomIt2 first, RandomIt2 last ) const; ``` | | | The member function called by the Searcher overload of `[std::search](../../algorithm/search "cpp/algorithm/search")` to perform a search with this searcher. `RandomIt2` must meet the requirements of [LegacyRandomAccessIterator](../../named_req/randomaccessiterator "cpp/named req/RandomAccessIterator"). `RandomIt1` and `RandomIt2` must have the same value type. ### Parameters | | | | | --- | --- | --- | | first, last | - | a pair of iterators designating the string to be examined | ### Return value If the pattern ([pat\_first, pat\_last)) is empty, returns `[std::make\_pair](http://en.cppreference.com/w/cpp/utility/pair/make_pair)(first, first)`. Otherwise, returns a pair of iterators to the first and one past last positions in [first, last) where a subsequence that compares equal to [pat\_first, pat\_last) as defined by `pred` is located, or `[std::make\_pair](http://en.cppreference.com/w/cpp/utility/pair/make_pair)(last, last)` otherwise. ### Notes | [Feature-test](../feature_test "cpp/utility/feature test") macro | | --- | | [`__cpp_lib_boyer_moore_searcher`](../../feature_test#Library_features "cpp/feature test") | ### Example ``` #include <iostream> #include <string> #include <algorithm> #include <functional> int main() { std::string in = "Lorem ipsum dolor sit amet, consectetur adipiscing elit," " sed do eiusmod tempor incididunt ut labore et dolore magna aliqua"; std::string needle = "pisci"; auto it = std::search(in.begin(), in.end(), std::boyer_moore_horspool_searcher( needle.begin(), needle.end())); if(it != in.end()) std::cout << "The string " << needle << " found at offset " << it - in.begin() << '\n'; else std::cout << "The string " << needle << " not found\n"; } ``` Output: ``` The string pisci found at offset 43 ``` ### See also | | | | --- | --- | | [search](../../algorithm/search "cpp/algorithm/search") | searches for a range of elements (function template) | | [default\_searcher](default_searcher "cpp/utility/functional/default searcher") (C++17) | standard C++ library search algorithm implementation (class template) | | [boyer\_moore\_searcher](boyer_moore_searcher "cpp/utility/functional/boyer moore searcher") (C++17) | Boyer-Moore search algorithm implementation (class template) | cpp std::binary_negate std::binary\_negate =================== | Defined in header `[<functional>](../../header/functional "cpp/header/functional")` | | | | --- | --- | --- | | ``` template< class Predicate > struct binary_negate : public std::binary_function< Predicate::first_argument_type, Predicate::second_argument_type, bool >; ``` | | (until C++11) | | ``` template< class Predicate > struct binary_negate; ``` | | (since C++11) (deprecated in C++17) (removed in C++20) | `binary_negate` is a wrapper function object returning the complement of the binary predicate it holds. The binary predicate type must define two member types, `first_argument_type` and `second_argument_type`, that are convertible to the predicate's parameter types. The function objects obtained from `[std::owner\_less](../../memory/owner_less "cpp/memory/owner less")`, `[std::ref](ref "cpp/utility/functional/ref")`, `[std::cref](ref "cpp/utility/functional/ref")`, `[std::plus](plus "cpp/utility/functional/plus")`, `[std::minus](minus "cpp/utility/functional/minus")`, `[std::multiplies](multiplies "cpp/utility/functional/multiplies")`, `[std::divides](divides "cpp/utility/functional/divides")`, `[std::modulus](modulus "cpp/utility/functional/modulus")`, `[std::equal\_to](equal_to "cpp/utility/functional/equal to")`, `[std::not\_equal\_to](not_equal_to "cpp/utility/functional/not equal to")`, `[std::greater](greater "cpp/utility/functional/greater")`, `[std::less](less "cpp/utility/functional/less")`, `[std::greater\_equal](greater_equal "cpp/utility/functional/greater equal")`, `[std::less\_equal](less_equal "cpp/utility/functional/less equal")`, `[std::logical\_not](logical_not "cpp/utility/functional/logical not")`, `[std::logical\_or](logical_or "cpp/utility/functional/logical or")`, `[std::bit\_and](bit_and "cpp/utility/functional/bit and")`, `[std::bit\_or](bit_or "cpp/utility/functional/bit or")`, `std::bit_xor`, `[std::mem\_fn](mem_fn "cpp/utility/functional/mem fn")`, `[std::map::value\_comp](../../container/map/value_comp "cpp/container/map/value comp")`, `[std::multimap::value\_comp](../../container/multimap/value_comp "cpp/container/multimap/value comp")`, `[std::function](function "cpp/utility/functional/function")`, or from a call to `[std::not2](not2 "cpp/utility/functional/not2")` have these types defined, as are function objects derived from the deprecated `[std::binary\_function](binary_function "cpp/utility/functional/binary function")`. `binary_negate` objects are easily constructed with helper function `[std::not2](not2 "cpp/utility/functional/not2")`. ### Member types | Type | Definition | | --- | --- | | `first_argument_type` | `Predicate::first_argument_type` | | `second_argument_type` | `Predicate::second_argument_type` | | `result_type` | `bool` | ### Member functions | | | | --- | --- | | (constructor) | constructs a new binary\_negate object with the supplied predicate (public member function) | | operator() | returns the logical complement of the result of a call to the stored predicate (public member function) | std::binary\_negate::binary\_negate ------------------------------------ | | | | | --- | --- | --- | | ``` explicit binary_negate( Predicate const& pred ); ``` | | (until C++14) | | ``` explicit constexpr binary_negate( Predicate const& pred ); ``` | | (since C++14) | Constructs a `binary_negate` function object with the stored predicate `pred`. ### Parameters | | | | | --- | --- | --- | | pred | - | predicate function object | std::binary\_negate::operator() -------------------------------- | | | | | --- | --- | --- | | ``` bool operator()( first_argument_type const& x, second_argument_type const& y ) const; ``` | | (until C++14) | | ``` constexpr bool operator()( first_argument_type const& x, second_argument_type const& y ) const; ``` | | (since C++14) | Returns the logical complement of the result of calling `pred(x, y)`. ### Parameters | | | | | --- | --- | --- | | x | - | first argument to pass through to predicate | | y | - | second argument to pass through to predicate | ### Return value The logical complement of the result of calling `pred(x, y)`. ### Example ``` #include <algorithm> #include <functional> #include <iostream> #include <vector> struct same : std::binary_function<int, int, bool> { bool operator()(int a, int b) const { return a == b; } }; int main() { std::vector<int> v1; std::vector<int> v2; for (int i = 0; i < 10; ++i) v1.push_back(i); for (int i = 0; i < 10; ++i) v2.push_back(10 - i); std::vector<bool> v3(v1.size()); std::binary_negate<same> not_same((same())); std::transform(v1.begin(), v1.end(), v2.begin(), v3.begin(), not_same); /* C++11 solution: // Use std::function<bool (int, int)> std::function<bool (int, int)> not_same = [](int x, int y)->bool{ return !same()(x, y); }; std::transform(v1.begin(), v1.end(), v2.begin(), v3.begin(), not_same); */ std::cout.setf(std::ios_base::boolalpha); for (int i = 0; i < 10; ++i) std::cout << v1[i] << ' ' << v2[i] << ' ' << v3[i] << '\n'; } ``` Output: ``` 0 10 true 1 9 true 2 8 true 3 7 true 4 6 true 5 5 false 6 4 true 7 3 true 8 2 true 9 1 true ``` ### See also | | | | --- | --- | | [binary\_function](binary_function "cpp/utility/functional/binary function") (deprecated in C++11)(removed in C++17) | adaptor-compatible binary function base class (class template) | | [function](function "cpp/utility/functional/function") (C++11) | wraps callable object of any copy constructible type with specified function call signature (class template) | | [move\_only\_function](move_only_function "cpp/utility/functional/move only function") (C++23) | wraps callable object of any type with specified function call signature (class template) | | [not2](not2 "cpp/utility/functional/not2") (deprecated in C++17)(removed in C++20) | constructs custom `std::binary_negate` object (function template) | | [ptr\_fun](ptr_fun "cpp/utility/functional/ptr fun") (deprecated in C++11)(removed in C++17) | creates an adaptor-compatible function object wrapper from a pointer to function (function template) | | [unary\_negate](unary_negate "cpp/utility/functional/unary negate") (deprecated in C++17)(removed in C++20) | wrapper function object returning the complement of the unary predicate it holds (class template) | cpp std::ranges::not_equal_to std::ranges::not\_equal\_to =========================== | Defined in header `[<functional>](../../../header/functional "cpp/header/functional")` | | | | --- | --- | --- | | ``` struct not_equal_to; ``` | | (since C++20) | Function object for performing comparisons. Deduces the parameter types of the function call operator from the arguments (but not the return type). ### Implementation-defined strict total order over pointers The function call operator yields the implementation-defined strict total order over pointers if the `=` operator between arguments invokes a built-in comparison operator for a pointer, even if the built-in `=` operator does not. The implementation-defined strict total order is consistent with the partial order imposed by built-in comparison operators (`<=>`, `<`, `>`, `<=`, and `>=`), and consistent among following standard function objects: * `[std::less](../less "cpp/utility/functional/less")`, `[std::greater](../greater "cpp/utility/functional/greater")`, `[std::less\_equal](../less_equal "cpp/utility/functional/less equal")`, and `[std::greater\_equal](../greater_equal "cpp/utility/functional/greater equal")`, when the template argument is a pointer type or `void` * [`std::ranges::equal_to`](equal_to "cpp/utility/functional/ranges/equal to"), **`std::ranges::not_equal_to`**, [`std::ranges::less`](less "cpp/utility/functional/ranges/less"), [`std::ranges::greater`](greater "cpp/utility/functional/ranges/greater"), [`std::ranges::less_equal`](less_equal "cpp/utility/functional/ranges/less equal"), [`std::ranges::greater_equal`](greater_equal "cpp/utility/functional/ranges/greater equal"), and `[std::compare\_three\_way](../../compare/compare_three_way "cpp/utility/compare/compare three way")` ### Member types | Member type | Definition | | --- | --- | | `is_transparent` | /\* unspecified \*/ | ### Member functions | | | | --- | --- | | operator() | checks if the arguments are *not equal* (public member function) | std::ranges::not\_equal\_to::operator() ---------------------------------------- | | | | | --- | --- | --- | | ``` template< class T, class U > requires std::equality_comparable_with<T, U> // with different sematic requirements constexpr bool operator()(T&& t, U&& u) const; ``` | | | Compares `t` and `u`. Equivalent to `return ![ranges::equal\_to](http://en.cppreference.com/w/cpp/ranges-functional-placeholder/equal_to){}([std::forward](http://en.cppreference.com/w/cpp/utility/forward)<T>(t), [std::forward](http://en.cppreference.com/w/cpp/utility/forward)<U>(u));`. ### Notes Unlike `[std::not\_equal\_to](../not_equal_to "cpp/utility/functional/not equal to")`, `std::ranges::not_equal_to` requires both `==` and `!=` to be valid (via the [`equality_comparable_with`](../../../concepts/equality_comparable "cpp/concepts/equality comparable") constraint), and is entirely defined in terms of `std::ranges::equal_to`. ### Example ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 3530](https://cplusplus.github.io/LWG/issue3530) | C++20 | syntactic checks were relaxed while comparing pointers | only semantic requirements relaxed | ### See also | | | | --- | --- | | [not\_equal\_to](../not_equal_to "cpp/utility/functional/not equal to") | function object implementing `x != y` (class template) |
programming_docs
cpp std::ranges::greater std::ranges::greater ==================== | Defined in header `[<functional>](../../../header/functional "cpp/header/functional")` | | | | --- | --- | --- | | ``` struct greater; ``` | | (since C++20) | Function object for performing comparisons. Deduces the parameter types of the function call operator from the arguments (but not the return type). ### Implementation-defined strict total order over pointers The function call operator yields the implementation-defined strict total order over pointers if the `<` operator between arguments invokes a built-in comparison operator for a pointer, even if the built-in `<` operator does not. The implementation-defined strict total order is consistent with the partial order imposed by built-in comparison operators (`<=>`, `<`, `>`, `<=`, and `>=`), and consistent among following standard function objects: * `[std::less](../less "cpp/utility/functional/less")`, `[std::greater](../greater "cpp/utility/functional/greater")`, `[std::less\_equal](../less_equal "cpp/utility/functional/less equal")`, and `[std::greater\_equal](../greater_equal "cpp/utility/functional/greater equal")`, when the template argument is a pointer type or `void` * [`std::ranges::equal_to`](equal_to "cpp/utility/functional/ranges/equal to"), [`std::ranges::not_equal_to`](not_equal_to "cpp/utility/functional/ranges/not equal to"), [`std::ranges::less`](less "cpp/utility/functional/ranges/less"), **`std::ranges::greater`**, [`std::ranges::less_equal`](less_equal "cpp/utility/functional/ranges/less equal"), [`std::ranges::greater_equal`](greater_equal "cpp/utility/functional/ranges/greater equal"), and `[std::compare\_three\_way](../../compare/compare_three_way "cpp/utility/compare/compare three way")` ### Member types | Member type | Definition | | --- | --- | | `is_transparent` | /\* unspecified \*/ | ### Member functions | | | | --- | --- | | operator() | checks if the first argument is *greater* than the second (public member function) | std::ranges::greater::operator() --------------------------------- | | | | | --- | --- | --- | | ``` template< class T, class U > requires std::totally_ordered_with<T, U> // with different semantic requirements constexpr bool operator()(T&& t, U&& u) const; ``` | | | Compares `t` and `u`. Equivalent to `return [ranges::less](http://en.cppreference.com/w/cpp/ranges-functional-placeholder/less){}([std::forward](http://en.cppreference.com/w/cpp/utility/forward)<U>(u), [std::forward](http://en.cppreference.com/w/cpp/utility/forward)<T>(t));`. ### Notes Unlike `[std::greater](../greater "cpp/utility/functional/greater")`, `std::ranges::greater` requires all six comparison operators `<`, `<=`, `>`, `>=`, `==` and `!=` to be valid (via the [`totally_ordered_with`](../../../concepts/totally_ordered "cpp/concepts/totally ordered") constraint) and is entirely defined in terms of `std::ranges::less`. ### Example ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 3530](https://cplusplus.github.io/LWG/issue3530) | C++20 | syntactic checks were relaxed while comparing pointers | only semantic requirements relaxed | ### See also | | | | --- | --- | | [greater](../greater "cpp/utility/functional/greater") | function object implementing `x > y` (class template) | cpp std::ranges::greater_equal std::ranges::greater\_equal =========================== | Defined in header `[<functional>](../../../header/functional "cpp/header/functional")` | | | | --- | --- | --- | | ``` struct greater_equal; ``` | | (since C++20) | Function object for performing comparisons. Deduces the parameter types of the function call operator from the arguments (but not the return type). ### Implementation-defined strict total order over pointers The function call operator yields the implementation-defined strict total order over pointers if the `<` operator between arguments invokes a built-in comparison operator for a pointer, even if the built-in `<` operator does not. The implementation-defined strict total order is consistent with the partial order imposed by built-in comparison operators (`<=>`, `<`, `>`, `<=`, and `>=`), and consistent among following standard function objects: * `[std::less](../less "cpp/utility/functional/less")`, `[std::greater](../greater "cpp/utility/functional/greater")`, `[std::less\_equal](../less_equal "cpp/utility/functional/less equal")`, and `[std::greater\_equal](../greater_equal "cpp/utility/functional/greater equal")`, when the template argument is a pointer type or `void` * [`std::ranges::equal_to`](equal_to "cpp/utility/functional/ranges/equal to"), [`std::ranges::not_equal_to`](not_equal_to "cpp/utility/functional/ranges/not equal to"), [`std::ranges::less`](less "cpp/utility/functional/ranges/less"), [`std::ranges::greater`](greater "cpp/utility/functional/ranges/greater"), [`std::ranges::less_equal`](less_equal "cpp/utility/functional/ranges/less equal"), **`std::ranges::greater_equal`**, and `[std::compare\_three\_way](../../compare/compare_three_way "cpp/utility/compare/compare three way")` ### Member types | Member type | Definition | | --- | --- | | `is_transparent` | /\* unspecified \*/ | ### Member functions | | | | --- | --- | | operator() | checks if the first argument is *greater* than or *equal* to the second (public member function) | std::ranges::greater\_equal::operator() ---------------------------------------- | | | | | --- | --- | --- | | ``` template< class T, class U > requires std::totally_ordered_with<T, U> // with different semantic requirements constexpr bool operator()(T&& t, U&& u) const; ``` | | | Compares `t` and `u`. Equivalent to `return ![ranges::less](http://en.cppreference.com/w/cpp/ranges-functional-placeholder/less){}([std::forward](http://en.cppreference.com/w/cpp/utility/forward)<T>(t), [std::forward](http://en.cppreference.com/w/cpp/utility/forward)<U>(u));`. ### Notes Unlike `[std::greater\_equal](../greater_equal "cpp/utility/functional/greater equal")`, `std::ranges::greater_equal` requires all six comparison operators `<`, `<=`, `>`, `>=`, `==` and `!=` to be valid (via the [`totally_ordered_with`](../../../concepts/totally_ordered "cpp/concepts/totally ordered") constraint) and is entirely defined in terms of `std::ranges::less`. ### Example ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 3530](https://cplusplus.github.io/LWG/issue3530) | C++20 | syntactic checks were relaxed while comparing pointers | only semantic requirements relaxed | ### See also | | | | --- | --- | | [greater\_equal](../greater_equal "cpp/utility/functional/greater equal") | function object implementing `x >= y` (class template) | cpp std::ranges::less_equal std::ranges::less\_equal ======================== | Defined in header `[<functional>](../../../header/functional "cpp/header/functional")` | | | | --- | --- | --- | | ``` struct less_equal; ``` | | (since C++20) | Function object for performing comparisons. Deduces the parameter types of the function call operator from the arguments (but not the return type). ### Implementation-defined strict total order over pointers The function call operator yields the implementation-defined strict total order over pointers if the `<` operator between arguments invokes a built-in comparison operator for a pointer, even if the built-in `<` operator does not. The implementation-defined strict total order is consistent with the partial order imposed by built-in comparison operators (`<=>`, `<`, `>`, `<=`, and `>=`), and consistent among following standard function objects: * `[std::less](../less "cpp/utility/functional/less")`, `[std::greater](../greater "cpp/utility/functional/greater")`, `[std::less\_equal](../less_equal "cpp/utility/functional/less equal")`, and `[std::greater\_equal](../greater_equal "cpp/utility/functional/greater equal")`, when the template argument is a pointer type or `void` * [`std::ranges::equal_to`](equal_to "cpp/utility/functional/ranges/equal to"), [`std::ranges::not_equal_to`](not_equal_to "cpp/utility/functional/ranges/not equal to"), [`std::ranges::less`](less "cpp/utility/functional/ranges/less"), [`std::ranges::greater`](greater "cpp/utility/functional/ranges/greater"), **`std::ranges::less_equal`**, [`std::ranges::greater_equal`](greater_equal "cpp/utility/functional/ranges/greater equal"), and `[std::compare\_three\_way](../../compare/compare_three_way "cpp/utility/compare/compare three way")` ### Member types | Member type | Definition | | --- | --- | | `is_transparent` | /\* unspecified \*/ | ### Member functions | | | | --- | --- | | operator() | checks if the first argument is *less* than or *equal* to the second (public member function) | std::ranges::less\_equal::operator() ------------------------------------- | | | | | --- | --- | --- | | ``` template< class T, class U > requires std::totally_ordered_with<T, U> // with different semantic requirements constexpr bool operator()(T&& t, U&& u) const; ``` | | | Compares `t` and `u`. Equivalent to `return ![ranges::less](http://en.cppreference.com/w/cpp/ranges-functional-placeholder/less){}([std::forward](http://en.cppreference.com/w/cpp/utility/forward)<U>(u), [std::forward](http://en.cppreference.com/w/cpp/utility/forward)<T>(t));`. ### Notes Unlike `[std::less\_equal](../less_equal "cpp/utility/functional/less equal")`, `std::ranges::less_equal` requires all six comparison operators `<`, `<=`, `>`, `>=`, `==` and `!=` to be valid (via the [`totally_ordered_with`](../../../concepts/totally_ordered "cpp/concepts/totally ordered") constraint) and is entirely defined in terms of `std::ranges::less`. ### Example ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 3530](https://cplusplus.github.io/LWG/issue3530) | C++20 | syntactic checks were relaxed while comparing pointers | only semantic requirements relaxed | ### See also | | | | --- | --- | | [less\_equal](../less_equal "cpp/utility/functional/less equal") | function object implementing `x <= y` (class template) | cpp std::reference_wrapper<T>::reference_wrapper std::reference\_wrapper<T>::reference\_wrapper ============================================== | | | | | --- | --- | --- | | | (1) | | | ``` template< class U > reference_wrapper( U&& x ) noexcept(/*see below*/) ; ``` | (until C++20) | | ``` template< class U > constexpr reference_wrapper( U&& x ) noexcept(/*see below*/) ; ``` | (since C++20) | | | (2) | | | ``` reference_wrapper( const reference_wrapper& other ) noexcept; ``` | (until C++20) | | ``` constexpr reference_wrapper( const reference_wrapper& other ) noexcept; ``` | (since C++20) | Constructs a new reference wrapper. 1) Converts `x` to `T&` as if by `T& t = [std::forward](http://en.cppreference.com/w/cpp/utility/forward)<U>(x);`, then stores a reference to `t`. This overload participates in overload resolution only if `typename [std::decay](http://en.cppreference.com/w/cpp/types/decay)<U>::type` is not the same type as `reference_wrapper` and the expression `FUN([std::declval](http://en.cppreference.com/w/cpp/utility/declval)<U>())` is well-formed, where `FUN` names the set of imaginary functions ``` void FUN(T&) noexcept; void FUN(T&&) = delete; ``` 2) Copy constructor. Stores a reference to `other.get()`. ### Parameters | | | | | --- | --- | --- | | x | - | an object to wrap | | other | - | another reference wrapper | ### Exceptions 1) [`noexcept`](../../../language/noexcept_spec "cpp/language/noexcept spec") specification: `noexcept(noexcept(FUN([std::declval](http://en.cppreference.com/w/cpp/utility/declval)<U>())))` where `FUN` is the set of imaginary functions described in the description above. ### Example ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 2993](https://cplusplus.github.io/LWG/issue2993) | C++11 | deleted `reference_wrapper(T&&)` constructor interferes with overload resolution in some cases | replaced with a constructor template | cpp deduction guides for std::reference_wrapper deduction guides for `std::reference_wrapper` ============================================= | Defined in header `[<functional>](../../../header/functional "cpp/header/functional")` | | | | --- | --- | --- | | ``` template<typename T> reference_wrapper(T&) -> reference_wrapper<T>; ``` | | (since C++17) | One [deduction guide](../../../language/class_template_argument_deduction "cpp/language/class template argument deduction") is provided for `[std::reference\_wrapper](../reference_wrapper "cpp/utility/functional/reference wrapper")` to support deduction of the sole class template parameter. ### Example ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 2981](https://cplusplus.github.io/LWG/issue2981) | C++17 | a redundant deduction guide from `reference_wrapper<T>` was provided | removed | | [LWG 2993](https://cplusplus.github.io/LWG/issue2993) | C++17 | defect resolution removed a constructor used for class template argument deduction | added deduction guide to compensate | cpp std::reference_wrapper<T>::operator() std::reference\_wrapper<T>::operator() ====================================== | | | | | --- | --- | --- | | ``` template< class... ArgTypes > typename std::result_of<T&(ArgTypes&&...)>::type operator() ( ArgTypes&&... args ) const; ``` | | (since C++11) (until C++17) | | ``` template< class... ArgTypes > std::invoke_result_t<T&, ArgTypes...> operator() ( ArgTypes&&... args ) const; ``` | | (since C++17) (until C++20) | | ``` template< class... ArgTypes > constexpr std::invoke_result_t<T&, ArgTypes...> operator() ( ArgTypes&&... args ) const; ``` | | (since C++20) | Calls the [Callable](../../../named_req/callable "cpp/named req/Callable") object, reference to which is stored. This function is available only if the stored reference points to a [Callable](../../../named_req/callable "cpp/named req/Callable") object. `T` must be a complete type. ### Parameters | | | | | --- | --- | --- | | args | - | arguments to pass to the called function | ### Return value The return value of the called function. ### Exceptions May throw implementation-defined exceptions. ### Example ``` #include <iostream> #include <functional> void f1() { std::cout << "reference to function called\n"; } void f2(int n) { std::cout << "bind expression called with " << n << " as the argument\n"; } int main() { std::reference_wrapper<void()> ref1 = std::ref(f1); ref1(); auto b = std::bind(f2, std::placeholders::_1); auto ref2 = std::ref(b); ref2(7); auto c = []{std::cout << "lambda function called\n"; }; auto ref3 = std::ref(c); ref3(); } ``` Output: ``` reference to function called bind expression called with 7 as the argument lambda function called ``` ### See also | | | | --- | --- | | [getoperator T&](get "cpp/utility/functional/reference wrapper/get") | accesses the stored reference (public member function) | cpp std::reference_wrapper<T>::operator= std::reference\_wrapper<T>::operator= ===================================== | | | | | --- | --- | --- | | ``` reference_wrapper& operator=( const reference_wrapper& other ) noexcept; ``` | | (since C++11) (until C++20) | | ``` constexpr reference_wrapper& operator=( const reference_wrapper& other ) noexcept; ``` | | (since C++20) | Copy assignment operator. Drops the current reference and stores a reference to `other.get()`. ### Parameters | | | | | --- | --- | --- | | other | - | reference wrapper to copy | ### Return values `*this`. cpp std::reference_wrapper<T>::get, std::reference_wrapper<T>::operator T& std::reference\_wrapper<T>::get, std::reference\_wrapper<T>::operator T& ======================================================================== | | | | | --- | --- | --- | | ``` operator T& () const noexcept; ``` | | (since C++11) (until C++20) | | ``` constexpr operator T& () const noexcept; ``` | | (since C++20) | | ``` T& get() const noexcept; ``` | | (since C++11) (until C++20) | | ``` constexpr T& get() const noexcept; ``` | | (since C++20) | Returns the stored reference. ### Parameters (none). ### Return value The stored reference. ### See also | | | | --- | --- | | [operator()](operator() "cpp/utility/functional/reference wrapper/operator()") | calls the stored function (public member function) | cpp std::move_only_function::swap std::move\_only\_function::swap =============================== | | | | | --- | --- | --- | | ``` void swap( move_only_function& other ) noexcept; ``` | | (since C++23) | Exchanges the stored callable objects of `*this` and `other`. ### Parameters | | | | | --- | --- | --- | | other | - | function wrapper to exchange the stored callable object with | ### Return value (none). ### See also | | | | --- | --- | | [swap](../function/swap "cpp/utility/functional/function/swap") | swaps the contents (public member function of `std::function<R(Args...)>`) | cpp std::move_only_function::operator bool std::move\_only\_function::operator bool ======================================== | | | | | --- | --- | --- | | ``` explicit operator bool() const noexcept; ``` | | (since C++23) | Checks whether `*this` stores a callable target, i.e. is not empty. ### Parameters (none). ### Return value `true` if `*this` stores a callable target, `false` otherwise. ### Example ``` #include <functional> #include <iostream> void sampleFunction() { std::cout << "This is the sample function!\n"; } void checkFunc( std::move_only_function<void() const> const &func ) { // Use operator bool to determine if callable target is available. if( func ) { std::cout << "Function is not empty! Calling function.\n"; func(); } else { std::cout << "Function is empty. Nothing to do.\n"; } } int main() { std::move_only_function<void() const> f1{}; std::move_only_function<void() const> f2{ sampleFunction }; std::cout << "f1: "; checkFunc(f1); std::cout << "f2: "; checkFunc(f2); } ``` Output: ``` f1: Function is empty. Nothing to do. f2: Function is not empty! Calling function. This is the sample function! ``` ### See also | | | | --- | --- | | [operator bool](../function/operator_bool "cpp/utility/functional/function/operator bool") | checks if a target is contained (public member function of `std::function<R(Args...)>`) | | | | --- | | | cpp std::move_only_function::operator() std::move\_only\_function::operator() ===================================== | | | | | --- | --- | --- | | ``` R operator()( Args... args ) /*cv*/ /*ref*/ noexcept(/*noex*/); ``` | | (since C++23) | Invokes the stored callable target with the parameters `args`. The `/*cv*/`, `/*ref*/`, and `/*noex*/` parts of `operator()` are identical to those of the template parameter of `std::move_only_function`. Equivalent to `return std::invoke\_r<R>(/\*cv-ref-cast\*/(f), [std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Args>(args)...);`, where `f` is a cv-unqualified lvalue that denotes the target object of `*this`, and `/*cv-ref-cast*/(f)` is equivalent to: * `f` if cv ref is either empty or `&`, or * `[std::as\_const](http://en.cppreference.com/w/cpp/utility/as_const)(f)` if cv ref is either `const` or `const &`, or * `std::move(f)` if cv ref is `&&`, or * `std::move([std::as\_const](http://en.cppreference.com/w/cpp/utility/as_const)(f))` if cv ref is `const &&`. The behavior is undefined if `*this` is empty. ### Parameters | | | | | --- | --- | --- | | args | - | parameters to pass to the stored callable target | ### Return value `std::invoke\_r<R>(/\*cv-ref-cast\*/(f), [std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Args>(args)...)`. ### Exceptions Propagates the exception thrown by the underlying function call. ### Example The following example shows how `std::move_only_function` can passed to other functions by value. Also, it shows how `std::move_only_function` can store lambdas. ``` #include <iostream> #include <functional> void call(std::move_only_function<int() const> f) // can be passed by value { std::cout << f() << '\n'; } int normal_function() { return 42; } int main() { int n = 1; auto lambda = [&n](){ return n; }; std::move_only_function<int() const> f = lambda; call(std::move(f)); n = 2; call(lambda); f = normal_function; call(std::move(f)); } ``` Output: ``` 1 2 42 ``` ### See also | | | | --- | --- | | [operator()](../function/operator() "cpp/utility/functional/function/operator()") | invokes the target (public member function of `std::function<R(Args...)>`) | | [operator()](../reference_wrapper/operator() "cpp/utility/functional/reference wrapper/operator()") | calls the stored function (public member function of `std::reference_wrapper<T>`) | | [invokeinvoke\_r](../invoke "cpp/utility/functional/invoke") (C++17)(C++23) | invokes any [Callable](../../../named_req/callable "cpp/named req/Callable") object with given arguments and possibility to specify return type (since C++23) (function template) |
programming_docs
cpp std::move_only_function::move_only_function std::move\_only\_function::move\_only\_function =============================================== | | | | | --- | --- | --- | | ``` move_only_function() noexcept; ``` | (1) | (since C++23) | | ``` move_only_function( std::nullptr_t ) noexcept; ``` | (2) | (since C++23) | | ``` move_only_function( move_only_function&& other ) noexcept; ``` | (3) | (since C++23) | | ``` move_only_function( const move_only_function& ) = delete; ``` | (4) | (since C++23) | | ``` template< class F > move_only_function( F&& f ); ``` | (5) | (since C++23) | | ``` template< class T, class... CArgs > explicit move_only_function( std::in_place_type_t<T>, CArgs&&... args ); ``` | (6) | (since C++23) | | ``` template< class T, class U, class... CArgs > explicit move_only_function( std::in_place_type_t<T>, std::initializer_list<U> il, CArgs&&... args ); ``` | (7) | (since C++23) | Creates a new `std::move_only_function`. 1-2) Default constructor and the constructor taking `nullptr` construct an empty `std::move_only_function`. 3) Move constructor constructs a `std::move_only_function` whose target is that of `other`. `other` is in a valid but unspecified state after move construction. 4) Copy constructor is deleted. `std::move_only_function` does not satisfy [CopyConstructible](../../../named_req/copyconstructible "cpp/named req/CopyConstructible"). 5) Let `VT` be `[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<F>`. If `f` is a null function pointer, a null pointer to member function, or an empty `std::move_only_function` (may be any specialization), then constructs an empty `std::move_only_function`. Otherwise, constructs a `std::move_only_function` whose target is of type `VT` and direct-non-list-initialized with `[std::forward](http://en.cppreference.com/w/cpp/utility/forward)<F>(f)`. * This overload participates in overload resolution only if `VT` is neither same as `move_only_function` nor a specialization of `[std::in\_place\_type\_t](../../in_place "cpp/utility/in place")`, and `/*is-callable-from*/<VT>` (see below) is `true`. * The program is ill-formed if `[std::is\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_constructible)<VT, F>` is not `true`. 6) Let `VT` be `[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<T>`. Constructs a `std::move_only_function` whose target is of type `VT` and direct-non-list-initialized with `[std::forward](http://en.cppreference.com/w/cpp/utility/forward)<CArgs>(args)...`. * This overload participates in overload resolution only if both `[std::is\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_constructible)<VT, CArgs...>` and `/*is-callable-from*/<VT>` (see below) are `true`. * The program is ill-formed if `VT` is not the same type as `T`. 7) Let `VT` be `[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<T>`. Constructs a `std::move_only_function` whose target is of type `VT` and direct-non-list-initialized with `il, [std::forward](http://en.cppreference.com/w/cpp/utility/forward)<CArgs>(args)...`. * This overload participates in overload resolution only if both `[std::is\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_constructible)<VT, [std::initializer\_list](http://en.cppreference.com/w/cpp/utility/initializer_list)<U>&, CArgs...>` and `/*is-callable-from*/<VT>` (see below) are `true`. * The program is ill-formed if `VT` is not the same type as `T`. For constructors (5-7), the behavior is undefined if `VT` does not satisfy the [Destructible](../../../named_req/destructible "cpp/named req/Destructible") requirements, or `[std::is\_move\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_move_constructible)<VT>` is `true` but `VT` does not satisfy the [MoveConstructible](../../../named_req/moveconstructible "cpp/named req/MoveConstructible") requirements. The constant `/*is-callable-from*/<VT>` is dependent on cv, ref, and noex in the template parameter of `std::move_only_function` as below: | cv ref `noexcept(`noex`)` | `/*is-callable-from*/<VT>` | | --- | --- | | `noexcept(false)` | `[std::is\_invocable\_r\_v](http://en.cppreference.com/w/cpp/types/is_invocable)<R, VT, Args...> && [std::is\_invocable\_r\_v](http://en.cppreference.com/w/cpp/types/is_invocable)<R, VT&, Args...>` | | `noexcept(true)` | `[std::is\_nothrow\_invocable\_r\_v](http://en.cppreference.com/w/cpp/types/is_invocable)<R, VT, Args...> && [std::is\_nothrow\_invocable\_r\_v](http://en.cppreference.com/w/cpp/types/is_invocable)<R, VT&, Args...>` | | `const noexcept(false)` | `[std::is\_invocable\_r\_v](http://en.cppreference.com/w/cpp/types/is_invocable)<R, const VT, Args...> && [std::is\_invocable\_r\_v](http://en.cppreference.com/w/cpp/types/is_invocable)<R, const VT&, Args...>` | | `const noexcept(true)` | `[std::is\_nothrow\_invocable\_r\_v](http://en.cppreference.com/w/cpp/types/is_invocable)<R, const VT, Args...> && [std::is\_nothrow\_invocable\_r\_v](http://en.cppreference.com/w/cpp/types/is_invocable)<R, const VT&, Args...>` | | `& noexcept(false)` | `[std::is\_invocable\_r\_v](http://en.cppreference.com/w/cpp/types/is_invocable)<R, VT&, Args...>` | | `& noexcept(true)` | `[std::is\_nothrow\_invocable\_r\_v](http://en.cppreference.com/w/cpp/types/is_invocable)<R, VT&, Args...>` | | `const & noexcept(false)` | `[std::is\_invocable\_r\_v](http://en.cppreference.com/w/cpp/types/is_invocable)<R, const VT&, Args...>` | | `const & noexcept(true)` | `[std::is\_nothrow\_invocable\_r\_v](http://en.cppreference.com/w/cpp/types/is_invocable)<R, const VT&, Args...>` | | `&& noexcept(false)` | `[std::is\_invocable\_r\_v](http://en.cppreference.com/w/cpp/types/is_invocable)<R, VT, Args...>` | | `&& noexcept(true)` | `[std::is\_nothrow\_invocable\_r\_v](http://en.cppreference.com/w/cpp/types/is_invocable)<R, VT, Args...>` | | `const && noexcept(false)` | `[std::is\_invocable\_r\_v](http://en.cppreference.com/w/cpp/types/is_invocable)<R, const VT, Args...>` | | `const && noexcept(true)` | `[std::is\_nothrow\_invocable\_r\_v](http://en.cppreference.com/w/cpp/types/is_invocable)<R, const VT, Args...>` | ### Parameters | | | | | --- | --- | --- | | other | - | another `std::move_only_function` to move from | | f | - | a function or a [Callable](../../../named_req/callable "cpp/named req/Callable") object to wrap | | args | - | arguments to construct the target object | | il | - | `[std::initializer\_list](../../initializer_list "cpp/utility/initializer list")` to construct the target object | ### Exceptions 5-7) May throw `[std::bad\_alloc](../../../memory/new/bad_alloc "cpp/memory/new/bad alloc")` on allocation failure or propagate the exception thrown by the initialization of the target. No exception is thrown if `VT` is a function pointer type or a specialization of `[std::reference\_wrapper](../reference_wrapper "cpp/utility/functional/reference wrapper")`. ### Example ### See also | | | | --- | --- | | [(constructor)](../function/function "cpp/utility/functional/function/function") | constructs a new `std::function` instance (public member function of `std::function<R(Args...)>`) | cpp swap(std::move_only_function) swap(std::move\_only\_function) =============================== | | | | | --- | --- | --- | | ``` friend void swap( move_only_function& lhs, move_only_function& rhs ) noexcept; ``` | | (since C++23) | Overloads the `[std::swap](../../../algorithm/swap "cpp/algorithm/swap")` algorithm for `std::move_only_function`. Exchanges the state of `lhs` with that of `rhs`. Effectively calls `lhs.swap(rhs)`. This function is not visible to ordinary [unqualified](../../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../../language/adl "cpp/language/adl") when `std::move_only_function<FunctionType>` is an associated class of the arguments. ### Parameters | | | | | --- | --- | --- | | lhs, rhs | - | `std::move_only_function` objects whose states to swap | ### Return value (none). ### Example ``` #include <concepts> #include <functional> #include <iostream> void foo(const char* str, int x) { std::cout << "foo(\"" << str << "\", " << x << ")\n"; } void bar(const char* str, int x) { std::cout << "bar(\"" << str << "\", " << x << ")\n"; } int main() { std::move_only_function<void(const char*, int) const> f1{ foo }; std::move_only_function<void(const char*, int) const> f2{ bar }; f1("f1", 1); f2("f2", 2); std::cout << "std::ranges::swap(f1, f2);\n"; std::ranges::swap(f1, f2); // finds the hidden friend f1("f1", 1); f2("f2", 2); } ``` Output: ``` foo("f1", 1) bar("f2", 2) std::ranges::swap(f1, f2); bar("f1", 1) foo("f2", 2) ``` ### See also | | | | --- | --- | | [swap](swap "cpp/utility/functional/move only function/swap") (C++23) | swaps the targets of two `std::move_only_function` objects (public member function) | | [std::swap(std::function)](../function/swap2 "cpp/utility/functional/function/swap2") (C++11) | specializes the `[std::swap](../../../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | cpp operator==(std::move_only_function) operator==(std::move\_only\_function) ===================================== | | | | | --- | --- | --- | | ``` friend bool operator==( const move_only_function& f, std::nullptr_t ) noexcept; ``` | | (since C++23) | Compares a `std::move_only_function` with `[std::nullptr\_t](../../../types/nullptr_t "cpp/types/nullptr t")`. Empty wrappers (that is, wrappers without a callable target) compare equal, non-empty functions compare non-equal. This function is not visible to ordinary [unqualified](../../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../../language/adl "cpp/language/adl") when `std::move_only_function<FunctionType>` is an associated class of the arguments. The `!=` operator is [synthesized](../../../language/operators#Relational_operators "cpp/language/operators") from `operator==`. ### Parameters | | | | | --- | --- | --- | | f | - | `std::move_only_function` to compare | ### Return value `!f`. ### Example ``` #include <functional> #include <iostream> using SomeVoidFunc = std::move_only_function<void(int) const>; class C { public: C() = default; C(SomeVoidFunc func) : void_func_(std::move(func)) {} void default_func(int i) const { std::cout << i << '\n'; }; void operator()() const { if (void_func_ == nullptr) // specialized compare with nullptr default_func(7); else void_func_(7); } private: SomeVoidFunc void_func_{}; }; void user_func(int i) { std::cout << (i + 1) << '\n'; } int main() { C c1; C c2(user_func); c1(); c2(); } ``` Output: ``` 7 8 ``` ### See also | | | | --- | --- | | [operator==operator!=](../function/operator_cmp "cpp/utility/functional/function/operator cmp") (removed in C++20) | compares a `[std::function](../function "cpp/utility/functional/function")` with `nullptr` (function template) | cpp std::move_only_function::operator= std::move\_only\_function::operator= ==================================== | | | | | --- | --- | --- | | ``` move_only_function& operator=( move_only_function&& other ); ``` | (1) | (since C++23) | | ``` move_only_function& operator=( const move_only_function& ) = delete; ``` | (2) | (since C++23) | | ``` move_only_function& operator=( std::nullptr_t ) noexcept; ``` | (3) | (since C++23) | | ``` template< class F > move_only_function& operator=( F&& f ); ``` | (4) | (since C++23) | Assigns a new target to `std::move_only_function` or destroys its target. 1) Moves the target of `other` to `*this` or destroys the target of `*this` (if any) if `other` is empty, by `auto(std::move(other)).swap(*this)`. `other` is in a valid state with an unspecified value after move assignment. 2) Copy assignment operator is deleted. `std::move_only_function` does not satisfy [CopyAssignable](../../../named_req/copyassignable "cpp/named req/CopyAssignable"). 3) Destroys the current target if it exists. `*this` is empty after the call. 4) Sets the target of `*this` to the callable `f`, or destroys the current target if `f` is a null function pointer, a null pointer to member function, or an empty `std::move_only_function`, as if by executing `move_only_function([std::forward](http://en.cppreference.com/w/cpp/utility/forward)<F>(f)).swap(\*this);`. This overload participates in overload resolution only if the constructor of `move_only_function` from `F` participates in overload resolution. The program is ill-formed or has undefined behavior if the selected constructor call is ill-formed or has undefined behavior. ### Parameters | | | | | --- | --- | --- | | other | - | another `std::move_only_function` object to move the target of | | f | - | a callable object to initialize the new target with | ### Return value `*this`. ### Notes It is intentional not to require the move assignment operator to be `noexcept` to leave room for an allocator-aware `move_only_function` in future. `move_only_function` can be assigned from `[std::in\_place\_type](http://en.cppreference.com/w/cpp/utility/in_place)<Fn>` given it can be constructed from that argument. ### See also | | | | --- | --- | | [operator=](../function/operator= "cpp/utility/functional/function/operator=") | assigns a new target (public member function of `std::function<R(Args...)>`) | | | | --- | | | cpp std::move_only_function::~move_only_function std::move\_only\_function::~move\_only\_function ================================================ | | | | | --- | --- | --- | | ``` ~move_only_function(); ``` | | (since C++23) | Destroys the `std::move_only_function` object. If the `std::move_only_function` is not empty, its target is also destroyed. ### See also | | | | --- | --- | | [(destructor)](../function/~function "cpp/utility/functional/function/~function") | destroys a `std::function` instance (public member function of `std::function<R(Args...)>`) | cpp std::function<R(Args...)>::~function std::function<R(Args...)>::~function ==================================== | | | | | --- | --- | --- | | ``` ~function(); ``` | | (since C++11) | Destroys the `[std::function](../function "cpp/utility/functional/function")` instance. If the `std::function` is not *empty*, its *target* is destroyed also. ### See also | | | | --- | --- | | [(destructor)](../move_only_function/~move_only_function "cpp/utility/functional/move only function/~move only function") (C++23) | destroys a `std::move_only_function` object (public member function of `std::move_only_function`) | cpp deduction guides for std::function deduction guides for `std::function` ==================================== | Defined in header `[<functional>](../../../header/functional "cpp/header/functional")` | | | | --- | --- | --- | | ``` template< class R, class... ArgTypes > function( R(*)(ArgTypes...) ) -> function<R(ArgTypes...)>; ``` | (1) | (since C++17) | | ``` template< class F > function( F ) -> function</*see below*/>; ``` | (2) | (since C++17) | | ``` template< class F > function( F ) -> function</*see below*/>; ``` | (3) | (since C++23) | | ``` template< class F > function( F ) -> function</*see below*/>; ``` | (4) | (since C++23) | 1) This [deduction guide](../../../language/class_template_argument_deduction "cpp/language/class template argument deduction") is provided for `[std::function](../function "cpp/utility/functional/function")` to allow deduction from functions. 2) This overload participates in overload resolution only if `&F::operator()` is well-formed when treated as an unevaluated operand and `decltype(&F::operator())` is of the form `R(G::*)(A...)` (optionally cv-qualified, optionally noexcept, optionally lvalue reference qualified). The deduced type is `[std::function](http://en.cppreference.com/w/cpp/utility/functional/function)<R(A...)>`. 3) This overload participates in overload resolution only if `&F::operator()` is well-formed when treated as an unevaluated operand and `F::operator()` is an [explicit object parameter function](../../../language/member_functions#Explicit_object_parameter "cpp/language/member functions") whose type is of form `R(G, A...)` or `R(G, A...) noexcept`. The deduced type is `[std::function](http://en.cppreference.com/w/cpp/utility/functional/function)<R(A...)>`. 4) This overload participates in overload resolution only if `&F::operator()` is well-formed when treated as an unevaluated operand and `F::operator()` is a [static member function](../../../language/static#Static_member_functions "cpp/language/static") whose type is of form `R(A...)` or `R(A...) noexcept`. The deduced type is `[std::function](http://en.cppreference.com/w/cpp/utility/functional/function)<R(A...)>`. ### Notes These deduction guides do not allow deduction from a function with [ellipsis parameter](../../../language/variadic_arguments "cpp/language/variadic arguments"), and the `...` in the types is always treated as a [pack expansion](../../../language/parameter_pack#Pack_expansion "cpp/language/parameter pack"). The type deduced by these deduction guides may change in a later standard revision (in particular, this might happen if `noexcept` support is added to `[std::function](../function "cpp/utility/functional/function")` in a later standard). ### Example ``` #include <functional> int func(double) { return 0; } int main() { std::function f{func}; // guide #1 deduces function<int(double)> int i = 5; std::function g = [&](double) { return i; }; // guide #2 deduces function<int(double)> } ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 3238](https://cplusplus.github.io/LWG/issue3238) | C++17 | behavior of (2) was unclear when`F::operator()` is &&-qualified | clarified to be excluded from overload resolution | cpp std::function<R(Args...)>::swap std::function<R(Args...)>::swap =============================== | | | | | --- | --- | --- | | ``` void swap( function& other ) noexcept; ``` | | (since C++11) | Exchanges the stored callable objects of `*this` and `other`. ### Parameters | | | | | --- | --- | --- | | other | - | function wrapper to exchange the stored callable object with | ### Return value (none). ### See also | | | | --- | --- | | [swap](../move_only_function/swap "cpp/utility/functional/move only function/swap") (C++23) | swaps the targets of two `std::move_only_function` objects (public member function of `std::move_only_function`) | cpp std::function<R(Args...)>::operator bool std::function<R(Args...)>::operator bool ======================================== | | | | | --- | --- | --- | | ``` explicit operator bool() const noexcept; ``` | | (since C++11) | Checks whether `*this` stores a callable function target, i.e. is not empty. ### Parameters (none). ### Return value `true` if `*this` stores a callable function target, `false` otherwise. ### Example ``` #include <functional> #include <iostream> void sampleFunction() { std::cout << "This is the sample function!\n"; } void checkFunc( std::function<void()> const &func ) { // Use operator bool to determine if callable target is available. if( func ) { std::cout << "Function is not empty! Calling function.\n"; func(); } else { std::cout << "Function is empty. Nothing to do.\n"; } } int main() { std::function<void()> f1; std::function<void()> f2( sampleFunction ); std::cout << "f1: "; checkFunc( f1 ); std::cout << "f2: "; checkFunc( f2 ); } ``` Output: ``` f1: Function is empty. Nothing to do. f2: Function is not empty! Calling function. This is the sample function! ``` ### See also | | | | --- | --- | | [operator bool](../move_only_function/operator_bool "cpp/utility/functional/move only function/operator bool") (C++23) | checks if the `std::move_only_function` has a target (public member function of `std::move_only_function`) | | | | --- | | |
programming_docs
cpp std::function<R(Args...)>::assign std::function<R(Args...)>::assign ================================= | | | | | --- | --- | --- | | ``` template< class F, class Alloc > void assign( F&& f, const Alloc& alloc ); ``` | | (since C++11) (removed in C++17) | Initializes the *target* with `f`. The `alloc` is used to allocate memory for any internal data structures that the `function` might use. Equivalent to `function([std::allocator\_arg](http://en.cppreference.com/w/cpp/memory/allocator_arg), alloc, [std::forward](http://en.cppreference.com/w/cpp/utility/forward)<F>(f)).swap(\*this);`. ### Parameters | | | | | --- | --- | --- | | f | - | callable function to initialize the *target* with | | alloc | - | allocator to use to allocate memory for the internal data structures | ### Return value (none). ### Exceptions May throw implementation-defined exceptions. ### See also | | | | --- | --- | | [operator=](operator= "cpp/utility/functional/function/operator=") | assigns a new target (public member function) | cpp std::function<R(Args...)>::operator() std::function<R(Args...)>::operator() ===================================== | | | | | --- | --- | --- | | ``` R operator()( Args... args ) const; ``` | | (since C++11) | Invokes the stored callable function target with the parameters `args`. Effectively does `INVOKE<R>(f, [std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Args>(args)...)`, where `f` is the target object of `*this` and `INVOKE` is the operation described in [Callable](../../../named_req/callable "cpp/named req/Callable"). ### Parameters | | | | | --- | --- | --- | | args | - | parameters to pass to the stored callable function target | ### Return value None if `R` is `void`. Otherwise the return value of the invocation of the stored callable object. ### Exceptions * `[std::bad\_function\_call](../bad_function_call "cpp/utility/functional/bad function call")` if `*this` does not store a callable function target, i.e. `!*this == true`. ### Example The following example shows how `[std::function](../function "cpp/utility/functional/function")` can be passed to other functions by value. Also, it shows how `[std::function](../function "cpp/utility/functional/function")` can store lambdas. ``` #include <iostream> #include <functional> void call(std::function<int()> f) // can be passed by value { std::cout << f() << '\n'; } int normal_function() { return 42; } int main() { int n = 1; std::function<int()> f = [&n](){ return n; }; call(f); n = 2; call(f); f = normal_function; call(f); } ``` Output: ``` 1 2 42 ``` ### See also | | | | --- | --- | | [operator()](../move_only_function/operator() "cpp/utility/functional/move only function/operator()") (C++23) | invokes the target (public member function of `std::move_only_function`) | | [operator()](../reference_wrapper/operator() "cpp/utility/functional/reference wrapper/operator()") | calls the stored function (public member function of `std::reference_wrapper<T>`) | | [bad\_function\_call](../bad_function_call "cpp/utility/functional/bad function call") (C++11) | the exception thrown when invoking an empty `[std::function](../function "cpp/utility/functional/function")` (class) | | [invokeinvoke\_r](../invoke "cpp/utility/functional/invoke") (C++17)(C++23) | invokes any [Callable](../../../named_req/callable "cpp/named req/Callable") object with given arguments and possibility to specify return type (since C++23) (function template) | cpp std::swap(std::function) std::swap(std::function) ======================== | Defined in header `[<functional>](../../../header/functional "cpp/header/functional")` | | | | --- | --- | --- | | ``` template< class R, class... Args > void swap( std::function<R(Args...)> &lhs, std::function<R(Args...)> &rhs ) noexcept; ``` | | (since C++11) | Overloads the `[std::swap](../../../algorithm/swap "cpp/algorithm/swap")` algorithm for `[std::function](../function "cpp/utility/functional/function")`. Exchanges the state of `lhs` with that of `rhs`. Effectively calls `lhs.swap(rhs)`. ### Parameters | | | | | --- | --- | --- | | lhs, rhs | - | polymorphic function wrappers whose states to swap | ### Return value (none). ### Example ``` #include <functional> #include <iostream> void foo(const char* str, int x) { std::cout << "foo(\"" << str << "\", " << x << ")\n"; } void bar(const char* str, int x) { std::cout << "bar(\"" << str << "\", " << x << ")\n"; } int main() { std::function<void(const char*, int)> f1{ foo }; std::function<void(const char*, int)> f2{ bar }; f1("f1", 1); f2("f2", 2); std::cout << "std::swap(f1, f2);\n"; std::swap(f1, f2); f1("f1", 1); f2("f2", 2); } ``` Output: ``` foo("f1", 1) bar("f2", 2) std::swap(f1, f2); bar("f1", 1) foo("f2", 2) ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 2062](https://cplusplus.github.io/LWG/issue2062) | C++11 | overload of `swap` for `function` was not required to be noexcept | required | ### See also | | | | --- | --- | | [swap](swap "cpp/utility/functional/function/swap") | swaps the contents (public member function) | | [swap(std::move\_only\_function)](../move_only_function/swap2 "cpp/utility/functional/move only function/swap2") (C++23) | overloads the `[std::swap](../../../algorithm/swap "cpp/algorithm/swap")` algorithm (function) | cpp std::function<R(Args...)>::target_type std::function<R(Args...)>::target\_type ======================================= | | | | | --- | --- | --- | | ``` const std::type_info& target_type() const noexcept; ``` | | (since C++11) | Returns the type of the stored function. ### Parameters (none). ### Return value `typeid(T)` if the stored function has type `T`, otherwise `typeid(void)`. ### Example ``` #include <functional> #include <iostream> int f(int a) { return -a; } void g(double) {} int main() { // fn1 and fn2 have the same type, but their targets do not std::function<int(int)> fn1(f), fn2([](int a) {return -a;}); std::cout << fn1.target_type().name() << '\n' << fn2.target_type().name() << '\n'; // since C++17 deduction guides (CTAD) can avail std::cout << std::function{g}.target_type().name() << '\n'; } ``` Possible output: ``` PFiiE Z4mainEUliE_ PFvdE ``` ### See also | | | | --- | --- | | [target](target "cpp/utility/functional/function/target") | obtains a pointer to the stored target (public member function) | cpp std::function<R(Args...)>::operator= std::function<R(Args...)>::operator= ==================================== | | | | | --- | --- | --- | | ``` function& operator=( const function& other ); ``` | (1) | (since C++11) | | ``` function& operator=( function&& other ); ``` | (2) | (since C++11) | | ``` function& operator=( std::nullptr_t ) noexcept; ``` | (3) | (since C++11) | | ``` template< class F > function& operator=( F&& f ); ``` | (4) | (since C++11) | | ``` template< class F > function& operator=( std::reference_wrapper<F> f ) noexcept; ``` | (5) | (since C++11) | Assigns a new *target* to `std::function`. 1) Assigns a copy of *target* of `other`, as if by executing `function(other).swap(*this);` 2) Moves the *target* of `other` to `*this`. `other` is in a valid state with an unspecified value. 3) Drops the current *target*. `*this` is *empty* after the call. 4) Sets the *target* of `*this` to the callable `f`, as if by executing `function([std::forward](http://en.cppreference.com/w/cpp/utility/forward)<F>(f)).swap(\*this);`. This operator does not participate in overload resolution unless `f` is [Callable](../../../named_req/callable "cpp/named req/Callable") for argument types `Args...` and return type `R`. 5) Sets the *target* of `*this` to a copy of `f`, as if by executing `function(f).swap(*this);` ### Parameters | | | | | --- | --- | --- | | other | - | another `std::function` object to copy the target of | | f | - | a callable to initialize the *target* with | | Type requirements | | -`F` must meet the requirements of [Callable](../../../named_req/callable "cpp/named req/Callable"). | ### Return value `*this`. ### Notes Even before allocator support was removed from `std::function` in C++17, these assignment operators use the default allocator rather than the allocator of `*this` or the allocator of `other` (see [LWG issue 2386](https://cplusplus.github.io/LWG/issue2386)). ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 2132](https://cplusplus.github.io/LWG/issue2132) | C++11 | the overload taking a Callable object might be ambiguous | constrained | | [LWG 2401](https://cplusplus.github.io/LWG/issue2401) | C++11 | assignment operator from `std::nullptr_t` not required to be noexcept | required | ### See also | | | | --- | --- | | [operator=](../move_only_function/operator= "cpp/utility/functional/move only function/operator=") (C++23) | replaces or destroys the target (public member function of `std::move_only_function`) | | [assign](assign "cpp/utility/functional/function/assign") (removed in C++17) | assigns a new target (public member function) | | | | --- | | | cpp std::function<R(Args...)>::target std::function<R(Args...)>::target ================================= | | | | | --- | --- | --- | | ``` template< class T > T* target() noexcept; ``` | (1) | (since C++11) | | ``` template< class T > const T* target() const noexcept; ``` | (2) | (since C++11) | Returns a pointer to the stored callable function target. ### Parameters (none). ### Return value A pointer to the stored function if `target_type() == typeid(T)`, otherwise a null pointer. ### Example ``` #include <functional> #include <iostream> int f(int, int) { return 1; } int g(int, int) { return 2; } void test(std::function<int(int, int)> const& arg) { std::cout << "test function: "; if (arg.target<std::plus<int>>()) std::cout << "it is plus\n"; if (arg.target<std::minus<int>>()) std::cout << "it is minus\n"; int (*const* ptr)(int, int) = arg.target<int(*)(int, int)>(); if (ptr && *ptr == f) std::cout << "it is the function f\n"; if (ptr && *ptr == g) std::cout << "it is the function g\n"; } int main() { test(std::function<int(int, int)>(std::plus<int>())); test(std::function<int(int, int)>(std::minus<int>())); test(std::function<int(int, int)>(f)); test(std::function<int(int, int)>(g)); } ``` Output: ``` test function: it is plus test function: it is minus test function: it is the function f test function: it is the function g ``` ### See also | | | | --- | --- | | [target\_type](target_type "cpp/utility/functional/function/target type") | obtains the `typeid` of the stored target (public member function) | cpp operator==,!=(std::function) operator==,!=(std::function) ============================ | Defined in header `[<functional>](../../../header/functional "cpp/header/functional")` | | | | --- | --- | --- | | ``` template< class R, class... ArgTypes > bool operator==( const std::function<R(ArgTypes...)>& f, std::nullptr_t ) noexcept; ``` | (1) | (since C++11) | | ``` template< class R, class... ArgTypes > bool operator==( std::nullptr_t, const std::function<R(ArgTypes...)>& f ) noexcept; ``` | (2) | (since C++11) (until C++20) | | ``` template< class R, class... ArgTypes > bool operator!=( const std::function<R(ArgTypes...)>& f, std::nullptr_t ) noexcept; ``` | (3) | (since C++11) (until C++20) | | ``` template< class R, class... ArgTypes > bool operator!=( std::nullptr_t, const std::function<R(ArgTypes...)>& f ) noexcept; ``` | (4) | (since C++11) (until C++20) | Compares a `std::function` with a null pointer. Empty functions (that is, functions without a callable target) compare equal, non-empty functions compare non-equal. | | | | --- | --- | | The `!=` operator is [synthesized](../../../language/operators#Relational_operators "cpp/language/operators") from `operator==`. | (since C++20) | ### Parameters | | | | | --- | --- | --- | | f | - | `std::function` to compare | ### Return value 1-2) `!f` 3-4) `(bool) f` ### Example ``` #include <functional> #include <iostream> using SomeVoidFunc = std::function<void(int)>; class C { public: C(SomeVoidFunc void_func = nullptr) : void_func_(void_func) { if (void_func_ == nullptr) { // specialized compare with nullptr void_func_ = std::bind(&C::default_func, this, std::placeholders::_1); } void_func_(7); } void default_func(int i) { std::cout << i << '\n'; }; private: SomeVoidFunc void_func_; }; void user_func(int i) { std::cout << (i + 1) << '\n'; } int main() { C c1; C c2(user_func); } ``` Output: ``` 7 8 ``` ### See also | | | | --- | --- | | [operator==](../move_only_function/operator== "cpp/utility/functional/move only function/operator==") (C++23) | compares a `std::move_only_function` with `nullptr` (function) | cpp std::function<R(Args...)>::function std::function<R(Args...)>::function =================================== | | | | | --- | --- | --- | | ``` function() noexcept; ``` | (1) | (since C++11) | | ``` function( std::nullptr_t ) noexcept; ``` | (2) | (since C++11) | | ``` function( const function& other ); ``` | (3) | (since C++11) | | | (4) | | | ``` function( function&& other ); ``` | (since C++11) (until C++20) | | ``` function( function&& other ) noexcept; ``` | (since C++20) | | ``` template< class F > function( F&& f ); ``` | (5) | (since C++11) | | ``` template< class Alloc > function( std::allocator_arg_t, const Alloc& alloc ) noexcept; ``` | (6) | (since C++11) (removed in C++17) | | ``` template< class Alloc > function( std::allocator_arg_t, const Alloc& alloc, std::nullptr_t ) noexcept; ``` | (7) | (since C++11) (removed in C++17) | | ``` template< class Alloc > function( std::allocator_arg_t, const Alloc& alloc, const function& other ); ``` | (8) | (since C++11) (removed in C++17) | | ``` template< class Alloc > function( std::allocator_arg_t, const Alloc& alloc, function&& other ); ``` | (9) | (since C++11) (removed in C++17) | | ``` template< class F, class Alloc > function( std::allocator_arg_t, const Alloc& alloc, F f ); ``` | (10) | (since C++11) (removed in C++17) | Constructs a `std::function` from a variety of sources. 1-2) Creates an *empty* function. 3-4) Copies (3) or moves (4) the *target* of `other` to the *target* of `*this`. If `other` is *empty*, `*this` will be *empty* after the call too. For (4), `other` is in a valid but unspecified state after the call. 5) Initializes the *target* with `[std::forward](http://en.cppreference.com/w/cpp/utility/forward)<F>(f)`. The *target* is of type `[std::decay](http://en.cppreference.com/w/cpp/types/decay)<F>::type`. If `f` is a null pointer to function, a null pointer to member, or an *empty* value of some `std::function` specialization, `*this` will be *empty* after the call. This constructor does not participate in overload resolution unless the target type is not same as `function`, and its lvalue is [Callable](../../../named_req/callable "cpp/named req/Callable") for argument types `Args...` and return type `R`. The program is ill-formed if the target type is not copy-constructible or initialization of the *target* is ill-formed. 6-10) Same as (1-5) except that `alloc` is used to allocate memory for any internal data structures that the `function` might use. When the *target* is a function pointer or a `[std::reference\_wrapper](../reference_wrapper "cpp/utility/functional/reference wrapper")`, small object optimization is guaranteed, that is, these targets are always directly stored inside the `[std::function](../function "cpp/utility/functional/function")` object, no dynamic allocation takes place. Other large objects may be constructed in dynamic allocated storage and accessed by the `[std::function](../function "cpp/utility/functional/function")` object through a pointer. ### Parameters | | | | | --- | --- | --- | | other | - | the function object used to initialize `*this` | | f | - | a callable object used to initialize `*this` | | alloc | - | an [Allocator](../../../named_req/allocator "cpp/named req/Allocator") used for internal memory allocation | | Type requirements | | -`[std::decay](http://en.cppreference.com/w/cpp/types/decay)<F>::type` must meet the requirements of [Callable](../../../named_req/callable "cpp/named req/Callable") and [CopyConstructible](../../../named_req/copyconstructible "cpp/named req/CopyConstructible"). | | -`Alloc` must meet the requirements of [Allocator](../../../named_req/allocator "cpp/named req/Allocator"). | ### Exceptions 3,8,9) Does not throw if `other`'s *target* is a function pointer or a `[std::reference\_wrapper](../reference_wrapper "cpp/utility/functional/reference wrapper")`, otherwise may throw `[std::bad\_alloc](../../../memory/new/bad_alloc "cpp/memory/new/bad alloc")` or any exception thrown by the constructor used to copy or move the stored callable object. | | | | --- | --- | | 4) Does not throw if `other`'s *target* is a function pointer or a `[std::reference\_wrapper](../reference_wrapper "cpp/utility/functional/reference wrapper")`, otherwise may throw `[std::bad\_alloc](../../../memory/new/bad_alloc "cpp/memory/new/bad alloc")` or any exception thrown by the constructor used to copy or move the stored callable object. | (until C++20) | 5,10) Does not throw if `f` is a function pointer or a `[std::reference\_wrapper](../reference_wrapper "cpp/utility/functional/reference wrapper")`, otherwise may throw `[std::bad\_alloc](../../../memory/new/bad_alloc "cpp/memory/new/bad alloc")` or any exception thrown by the copy constructor of the stored callable object. ### Notes `std::function`'s allocator support was poorly specified and inconsistently implemented. Some implementations do not provide overloads (6-10) at all, some provide the overloads but ignore the supplied allocator argument, and some provide the overloads and use the supplied allocator for construction but not when the `std::function` is reassigned. As a result, allocator support was removed in C++17. ### Example ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 2132](https://cplusplus.github.io/LWG/issue2132) | C++11 | constructor taking a Callable object might be ambiguous | constrained | | [LWG 2774](https://cplusplus.github.io/LWG/issue2774) | C++11 | constructor taking a Callable performed an additional move | eliminated | ### See also | | | | --- | --- | | [(constructor)](../move_only_function/move_only_function "cpp/utility/functional/move only function/move only function") (C++23) | constructs a new `std::move_only_function` object (public member function of `std::move_only_function`) |
programming_docs
cpp deduction guides for std::pair deduction guides for `std::pair` ================================ | Defined in header `[<utility>](../../header/utility "cpp/header/utility")` | | | | --- | --- | --- | | ``` template<class T1, class T2> pair(T1, T2) -> pair<T1, T2>; ``` | | (since C++17) | One [deduction guide](../../language/class_template_argument_deduction "cpp/language/class template argument deduction") is provided for `[std::pair](../pair "cpp/utility/pair")` to account for the edge cases missed by the implicit deduction guides. In particular, non-copyable arguments and array to pointer conversion. ### Example ``` #include <utility> int main() { int a[2], b[3]; std::pair p{a, b}; // explicit deduction guide is used in this case } ``` cpp std::pair<T1,T2>::pair std::pair<T1,T2>::pair ====================== | | | | | --- | --- | --- | | | (1) | | | ``` pair(); ``` | (until C++11) | | ``` constexpr pair(); ``` | (since C++11) (conditionally explicit) | | | (2) | | | ``` pair( const T1& x, const T2& y ); ``` | (until C++11) | | ``` pair( const T1& x, const T2& y ); ``` | (since C++11) (until C++14) (conditionally explicit) | | ``` constexpr pair( const T1& x, const T2& y ); ``` | (since C++14) (conditionally explicit) | | | (3) | | | ``` template< class U1, class U2 > pair( U1&& x, U2&& y ); ``` | (since C++11) (until C++14) (conditionally explicit) | | ``` template< class U1, class U2 > constexpr pair( U1&& x, U2&& y ); ``` | (since C++14) (until C++23) (conditionally explicit) | | ``` template< class U1 = T1, class U2 = T2 > constexpr pair( U1&& x, U2&& y ); ``` | (since C++23) (conditionally explicit) | | ``` template< class U1, class U2 > constexpr pair( pair<U1, U2>& p ); ``` | (4) | (since C++23) (conditionally explicit) | | | (5) | | | ``` template< class U1, class U2 > pair( const pair<U1, U2>& p ); ``` | (until C++11) | | ``` template< class U1, class U2 > pair( const pair<U1, U2>& p ); ``` | (since C++11) (until C++14) (conditionally explicit) | | ``` template< class U1, class U2 > constexpr pair( const pair<U1, U2>& p ); ``` | (since C++14) (conditionally explicit) | | | (6) | | | ``` template< class U1, class U2 > pair( pair<U1, U2>&& p ); ``` | (since C++11) (until C++14) (conditionally explicit) | | ``` template< class U1, class U2 > constexpr pair( pair<U1, U2>&& p ); ``` | (since C++14) (conditionally explicit) | | ``` template< class U1, class U2 > constexpr pair( const pair<U1, U2>&& p ); ``` | (7) | (since C++23) (conditionally explicit) | | | (8) | | | ``` template< class... Args1, class... Args2 > pair( std::piecewise_construct_t, std::tuple<Args1...> first_args, std::tuple<Args2...> second_args ); ``` | (since C++11) (until C++20) | | ``` template< class... Args1, class... Args2 > constexpr pair( std::piecewise_construct_t, std::tuple<Args1...> first_args, std::tuple<Args2...> second_args ); ``` | (since C++20) | | ``` pair( const pair& p ) = default; ``` | (9) | | | ``` pair( pair&& p ) = default; ``` | (10) | (since C++11) | Constructs a new pair. 1) Default constructor. Value-initializes both elements of the pair, `first` and `second`. | | | | --- | --- | | * This constructor participates in overload resolution if and only if `[std::is\_default\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_default_constructible)<T1>` and `[std::is\_default\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_default_constructible)<T2>` are both `true`. * This constructor is `explicit` if and only if either `T1` or `T2` is not implicitly default-constructible. | (since C++11) | 2) Initializes `first` with `x` and `second` with `y`. | | | | --- | --- | | * This constructor participates in overload resolution if and only if `[std::is\_copy\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_copy_constructible)<T1>` and `[std::is\_copy\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_copy_constructible)<T2>` are both `true`. * This constructor is `explicit` if and only if `[std::is\_convertible\_v](http://en.cppreference.com/w/cpp/types/is_convertible)<const T1&, T1>` is `false` or `[std::is\_convertible\_v](http://en.cppreference.com/w/cpp/types/is_convertible)<const T2&, T2>` is `false`. | (since C++11) | 3) Initializes `first` with `[std::forward](http://en.cppreference.com/w/cpp/utility/forward)<U1>(x)` and `second` with `[std::forward](http://en.cppreference.com/w/cpp/utility/forward)<U2>(y)`. * This constructor participates in overload resolution if and only if `[std::is\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_constructible)<T1, U1>` and `[std::is\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_constructible)<T2, U2>` are both `true`. * This constructor is `explicit` if and only if `[std::is\_convertible\_v](http://en.cppreference.com/w/cpp/types/is_convertible)<U1, T1>` is `false` or `[std::is\_convertible\_v](http://en.cppreference.com/w/cpp/types/is_convertible)<U2, T2>` is `false`. | | | | --- | --- | | * This constructor is defined as deleted if the initialization of `first` or `second` would [bind a reference to temporary object](../../language/reference_initialization#Lifetime_of_a_temporary_object "cpp/language/reference initialization"). | (since C++23) | 4) Initializes `first` with `p.first` and `second` with `p.second`. * This constructor participates in overload resolution if and only if `[std::is\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_constructible)<T1, U1&>` and `[std::is\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_constructible)<T2, U2&>` are both `true`. * This constructor is `explicit` if and only if `[std::is\_convertible\_v](http://en.cppreference.com/w/cpp/types/is_convertible)<U1&, T1>` is `false` or `[std::is\_convertible\_v](http://en.cppreference.com/w/cpp/types/is_convertible)<U2&, T2>` is `false`. * This constructor is defined as deleted if the initialization of `first` or `second` would bind a reference to temporary object. 5) Initializes `first` with `p.first` and `second` with `p.second`. | | | | --- | --- | | * This constructor participates in overload resolution if and only if `[std::is\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_constructible)<T1, const U1&>` and `[std::is\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_constructible)<T2, const U2&>` are both `true`. * This constructor is `explicit` if and only if `[std::is\_convertible\_v](http://en.cppreference.com/w/cpp/types/is_convertible)<const U1&, T1>` is `false` or `[std::is\_convertible\_v](http://en.cppreference.com/w/cpp/types/is_convertible)<const U2&, T2>` is `false`. | (since C++11) | | | | | --- | --- | | * This constructor is defined as deleted if the initialization of `first` or `second` would bind a reference to temporary object. | (since C++23) | 6) Initializes `first` with `[std::forward](http://en.cppreference.com/w/cpp/utility/forward)<U1>(p.first)` and `second` with `[std::forward](http://en.cppreference.com/w/cpp/utility/forward)<U2>(p.second)`. * This constructor participates in overload resolution if and only if `[std::is\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_constructible)<T1, U1>` and `[std::is\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_constructible)<T2, U2>` are both `true`. * This constructor is `explicit` if and only if `[std::is\_convertible\_v](http://en.cppreference.com/w/cpp/types/is_convertible)<U1, T1>` is `false` or `[std::is\_convertible\_v](http://en.cppreference.com/w/cpp/types/is_convertible)<U2, T2>` is `false`. | | | | --- | --- | | * This constructor is defined as deleted if the initialization of `first` or `second` would bind a reference to temporary object. | (since C++23) | 7) Initializes `first` with `[std::forward](http://en.cppreference.com/w/cpp/utility/forward)<const U1>(p.first)` and `second` with `[std::forward](http://en.cppreference.com/w/cpp/utility/forward)<const U2>(p.second)`. * This constructor participates in overload resolution if and only if `[std::is\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_constructible)<T1, U1>` and `[std::is\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_constructible)<T2, U2>` are both `true`. * This constructor is `explicit` if and only if `[std::is\_convertible\_v](http://en.cppreference.com/w/cpp/types/is_convertible)<const U1, T1>` is `false` or `[std::is\_convertible\_v](http://en.cppreference.com/w/cpp/types/is_convertible)<const U2, T2>` is `false`. * This constructor is defined as deleted if the initialization of `first` or `second` would bind a reference to temporary object. 8) Forwards the elements of `first_args` to the constructor of `first` and forwards the elements of `second_args` to the constructor of `second`. This is the only non-default constructor that can be used to create a pair of non-copyable non-movable types. The program is ill-formed if `first` or `second` is a reference and bound to a temporary object. 9) Copy constructor is implicitly declared (until C++11)defaulted, and is `constexpr` if copying of both elements satisfies the requirements on constexpr functions (since C++11). 10) Move constructor is defaulted, and is `constexpr` if moving of both elements satisfies the requirements on constexpr functions. ### Parameters | | | | | --- | --- | --- | | x | - | value to initialize the first element of this pair | | y | - | value to initialize the second element of this pair | | p | - | pair of values used to initialize both elements of this pair | | first\_args | - | tuple of constructor arguments to initialize the first element of this pair | | second\_args | - | tuple of constructor arguments to initialize the second element of this pair | ### Exceptions Does not throw exceptions unless one of the specified operations (e.g. constructor of an element) throws. ### Example ``` #include <utility> #include <string> #include <complex> #include <tuple> #include <iostream> int main() { auto print = [](auto rem, auto const& pair) { std::cout << rem << "(" << pair.first << ", " << pair.second << ")\n"; }; std::pair<int, float> p1; print("(1) Value-initialized: ", p1); std::pair<int, double> p2{42, 3.1415}; print("(2) Initialized with two values: ", p2); std::pair<char, int> p4{p2}; print("(4) Implicitly converted: ", p4); std::pair<std::complex<double>, std::string> p6{ std::piecewise_construct, std::forward_as_tuple(0.123, 7.7), std::forward_as_tuple(10, 'a')}; print("(8) Piecewise constructed: ", p6); } ``` Possible output: ``` (1) Value-initialized: (0, 0) (2) Initialized with two values: (42, 3.1415) (4) Implicitly converted: (*, 3) (8) Piecewise constructed: ((0.123,7.7), aaaaaaaaaa) ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [N4387](https://wg21.link/N4387) | C++11 | some constructors were implicit-only, preventing some uses | constructors made conditionally-explicit | | [LWG 2510](https://cplusplus.github.io/LWG/issue2510) | C++11 | default constructor was implicit | made conditionally-explicit | ### See also | | | | --- | --- | | [make\_pair](make_pair "cpp/utility/pair/make pair") | creates a `pair` object of type, defined by the argument types (function template) | | [(constructor)](../tuple/tuple "cpp/utility/tuple/tuple") (C++11) | constructs a new `tuple` (public member function of `std::tuple<Types...>`) | cpp std::pair<T1,T2>::swap std::pair<T1,T2>::swap ====================== | | | | | --- | --- | --- | | | (1) | | | ``` void swap( pair& other ) noexcept(/* see below */); ``` | (since C++11) (until C++20) | | ``` constexpr void swap( pair& other ) noexcept(/* see below */); ``` | (since C++20) | | ``` constexpr void swap( const pair& other ) const noexcept(/* see below */); ``` | (2) | (since C++23) | Swaps `first` with `other.first` and `second` with `other.second`, as if by `using [std::swap](http://en.cppreference.com/w/cpp/algorithm/swap); swap(first, other.first); swap(second, other.second);`. | | | | --- | --- | | If either selected `swap` function call is ill-formed or does not swap the value of the member, the behavior is undefined. | (until C++23) | | 1) The program is ill-formed if either `[std::is\_swappable\_v](http://en.cppreference.com/w/cpp/types/is_swappable)<T1>` or `[std::is\_swappable\_v](http://en.cppreference.com/w/cpp/types/is_swappable)<T2>` is not `true`. 2) The program is ill-formed if either `[std::is\_swappable\_v](http://en.cppreference.com/w/cpp/types/is_swappable)<const T1>` or `[std::is\_swappable\_v](http://en.cppreference.com/w/cpp/types/is_swappable)<const T2>` is not `true`. If either selected `swap` function call does not swap the value of the member, the behavior is undefined. | (since C++23) | ### Parameters | | | | | --- | --- | --- | | other | - | pair of values to swap | ### Return value (none). ### Exceptions | | | | --- | --- | | [`noexcept`](../../language/noexcept_spec "cpp/language/noexcept spec") specification: `noexcept( noexcept(swap(first, other.first)) && noexcept(swap(second, other.second)) )` In the expression above, the identifier `swap` is looked up in the same manner as the one used by the C++17 `[std::is\_nothrow\_swappable](../../types/is_swappable "cpp/types/is swappable")` trait. | (until C++17) | | 1) [`noexcept`](../../language/noexcept_spec "cpp/language/noexcept spec") specification: `noexcept( [std::is\_nothrow\_swappable\_v](http://en.cppreference.com/w/cpp/types/is_swappable)<first\_type> && [std::is\_nothrow\_swappable\_v](http://en.cppreference.com/w/cpp/types/is_swappable)<second\_type> )` 2) [`noexcept`](../../language/noexcept_spec "cpp/language/noexcept spec") specification: `noexcept( [std::is\_nothrow\_swappable\_v](http://en.cppreference.com/w/cpp/types/is_swappable)<const first\_type> && [std::is\_nothrow\_swappable\_v](http://en.cppreference.com/w/cpp/types/is_swappable)<const second\_type> )` | (since C++17) | ### Example ``` #include <iostream> #include <utility> #include <string> int main() { std::pair<int, std::string> p1(10, "test"), p2; p2.swap(p1); std::cout << "(" << p2.first << ", " << p2.second << ")\n"; #if __cpp_lib_ranges_zip >= 202110L // Using the C++23 const qualified swap overload // (swap is no longer propagating pair constness) int i1 = 10, i2{}; std::string s1("test"), s2; const std::pair<int&, std::string&> r1(i1, s1), r2(i2, s2); r2.swap(r1); std::cout << "(" << i2 << ", " << s2 << ")\n"; #endif } ``` Possible output: ``` (10, test) (10, test) ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 2456](https://cplusplus.github.io/LWG/issue2456) | C++11 | the `noexcept` specification is ill-formed | made to work | ### See also | | | | --- | --- | | [swap](../../algorithm/swap "cpp/algorithm/swap") | swaps the values of two objects (function template) | | [swap](../tuple/swap "cpp/utility/tuple/swap") (C++11) | swaps the contents of two `tuple`s (public member function of `std::tuple<Types...>`) | cpp std::make_pair std::make\_pair =============== | Defined in header `[<utility>](../../header/utility "cpp/header/utility")` | | | | --- | --- | --- | | ``` template< class T1, class T2 > std::pair<T1,T2> make_pair( T1 t, T2 u ); ``` | | (until C++11) | | ``` template< class T1, class T2 > std::pair<V1,V2> make_pair( T1&& t, T2&& u ); ``` | | (since C++11) (until C++14) | | ``` template< class T1, class T2 > constexpr std::pair<V1,V2> make_pair( T1&& t, T2&& u ); ``` | | (since C++14) | Creates a `[std::pair](../pair "cpp/utility/pair")` object, deducing the target type from the types of arguments. | | | | --- | --- | | The deduced types `V1` and `V2` are `[std::decay](http://en.cppreference.com/w/cpp/types/decay)<T1>::type` and `[std::decay](http://en.cppreference.com/w/cpp/types/decay)<T2>::type` (the usual type transformations applied to arguments of functions passed by value) unless application of `[std::decay](../../types/decay "cpp/types/decay")` results in `[std::reference\_wrapper](http://en.cppreference.com/w/cpp/utility/functional/reference_wrapper)<X>` for some type `X`, in which case the deduced type is `X&`. | (since C++11) | ### Parameters | | | | | --- | --- | --- | | t, u | - | the values to construct the pair from | ### Return value A `[std::pair](../pair "cpp/utility/pair")` object containing the given values. ### Example ``` #include <iostream> #include <utility> #include <functional> int main() { int n = 1; int a[5] = {1, 2, 3, 4, 5}; // build a pair from two ints auto p1 = std::make_pair(n, a[1]); std::cout << "The value of p1 is " << "(" << p1.first << ", " << p1.second << ")\n"; // build a pair from a reference to int and an array (decayed to pointer) auto p2 = std::make_pair(std::ref(n), a); n = 7; std::cout << "The value of p2 is " << "(" << p2.first << ", " << *(p2.second + 2) << ")\n"; } ``` Output: ``` The value of p1 is (1, 2) The value of p2 is (7, 3) ``` cpp std::swap(std::pair) std::swap(std::pair) ==================== | Defined in header `[<utility>](../../header/utility "cpp/header/utility")` | | | | --- | --- | --- | | | (1) | | | ``` template< class T1, class T2 > void swap( std::pair<T1,T2>& x, std::pair<T1,T2>& y ) noexcept(/* see below */); ``` | (since C++11) (until C++20) | | ``` template< class T1, class T2 > constexpr void swap( std::pair<T1,T2>& x, std::pair<T1,T2>& y ) noexcept(/* see below */); ``` | (since C++20) | | ``` template< class T1, class T2 > constexpr void swap( const std::pair<T1,T2>& x, const std::pair<T1,T2>& y ) noexcept(/* see below */); ``` | (2) | (since C++23) | Swaps the contents of `x` and `y`. Equivalent to `x.swap(y)`. | | | | --- | --- | | 1) This overload participates in overload resolution only if `[std::is\_swappable\_v](http://en.cppreference.com/w/cpp/types/is_swappable)<first_type> && [std::is\_swappable\_v](http://en.cppreference.com/w/cpp/types/is_swappable)<second_type>` is `true`. 2) This overload participates in overload resolution only if `[std::is\_swappable\_v](http://en.cppreference.com/w/cpp/types/is_swappable)<const first_type> && [std::is\_swappable\_v](http://en.cppreference.com/w/cpp/types/is_swappable)<const second_type>` is `true`. | (since C++17) | ### Parameters | | | | | --- | --- | --- | | x, y | - | pairs whose contents to swap | ### Return value (none). ### Exceptions [`noexcept`](../../language/noexcept_spec "cpp/language/noexcept spec") specification: `noexcept(noexcept(x.swap(y)))` ### See also | | | | --- | --- | | [swap](../../algorithm/swap "cpp/algorithm/swap") | swaps the values of two objects (function template) | | [std::swap(std::tuple)](../tuple/swap2 "cpp/utility/tuple/swap2") (C++11) | specializes the `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | cpp std::pair<T1,T2>::operator= std::pair<T1,T2>::operator= =========================== | | | | | --- | --- | --- | | | (1) | | | ``` pair& operator=( const pair& other ); ``` | (until C++20) | | ``` constexpr pair& operator=( const pair& other ); ``` | (since C++20) | | ``` constexpr const pair& operator=( const pair& other ) const; ``` | (2) | (since C++23) | | | (3) | | | ``` template< class U1, class U2 > pair& operator=( const pair<U1, U2>& other ); ``` | (since C++11) (until C++20) | | ``` template< class U1, class U2 > constexpr pair& operator=( const pair<U1, U2>& other ); ``` | (since C++20) | | ``` template< class U1, class U2 > constexpr const pair& operator=( const pair<U1, U2>& other ) const; ``` | (4) | (since C++23) | | | (5) | | | ``` pair& operator=( pair&& other ) noexcept(/* see below */); ``` | (since C++11) (until C++20) | | ``` constexpr pair& operator=( pair&& other ) noexcept(/* see below */); ``` | (since C++20) | | ``` constexpr const pair& operator=( pair&& other ) const; ``` | (6) | (since C++23) | | | (7) | | | ``` template< class U1, class U2 > pair& operator=( pair<U1, U2>&& other ); ``` | (since C++11) (until C++20) | | ``` template< class U1, class U2 > constexpr pair& operator=( pair<U1, U2>&& other ); ``` | (since C++20) | | ``` template< class U1, class U2 > constexpr const pair& operator=( pair<U1, U2>&& other ) const; ``` | (8) | (since C++23) | Replaces the contents of the pair. 1) Copy assignment operator. Replaces the contents with a copy of the contents of other. | | | | --- | --- | | * The assignment operator is implicitly declared. Using this assignment operator makes the program ill-formed if either `T1` or `T2` is a const-qualified type, or a reference type, or a class type with an inaccessible copy assignment operator, or an array type of such class. | (until C++11) | | * This overload is defined as deleted if either `[std::is\_copy\_assignable](http://en.cppreference.com/w/cpp/types/is_copy_assignable)<T1>::value` or `[std::is\_copy\_assignable](http://en.cppreference.com/w/cpp/types/is_copy_assignable)<T2>::value` is `false`. | (since C++11) | 2) Copy assignment operator for const-qualified operand. * This overload participates in overload resolution only if `[std::is\_copy\_assignable\_v](http://en.cppreference.com/w/cpp/types/is_copy_assignable)<const T1>` and `[std::is\_copy\_assignable\_v](http://en.cppreference.com/w/cpp/types/is_copy_assignable)<const T2>` are both `true`. 3) Assigns `other.first` to `first` and `other.second` to `second`. * This overload participates in overload resolution only if `[std::is\_assignable](http://en.cppreference.com/w/cpp/types/is_assignable)<T1&, const U1&>::value` and `[std::is\_assignable](http://en.cppreference.com/w/cpp/types/is_assignable)<T2&, const U2&>::value` are both `true`. 4) Assigns `other.first` to `first` and `other.second` to `second`. * This overload participates in overload resolution only if `[std::is\_assignable\_v](http://en.cppreference.com/w/cpp/types/is_assignable)<const T1&, const U1&>` and `[std::is\_assignable\_v](http://en.cppreference.com/w/cpp/types/is_assignable)<const T2&, const U2&>` are both `true`. 5) Move assignment operator. Replaces the contents with those of `other` using move semantics. * This overload participates in overload resolution only if `[std::is\_move\_assignable](http://en.cppreference.com/w/cpp/types/is_move_assignable)<T1>::value` and `[std::is\_move\_assignable](http://en.cppreference.com/w/cpp/types/is_move_assignable)<T2>::value` are both `true`. 6) Move assignment operator for const-qualified operand. * This overload participates in overload resolution only if `[std::is\_assignable\_v](http://en.cppreference.com/w/cpp/types/is_assignable)<const T1&, T1>` and `[std::is\_assignable\_v](http://en.cppreference.com/w/cpp/types/is_assignable)<const T2&, T2>` are both `true`. 7) Assigns `[std::forward](http://en.cppreference.com/w/cpp/utility/forward)<U1>(p.first)` to `first` and `[std::forward](http://en.cppreference.com/w/cpp/utility/forward)<U2>(p.second)` to `second`. * This overload participates in overload resolution only if `[std::is\_assignable](http://en.cppreference.com/w/cpp/types/is_assignable)<T1&, U1>::value` and `[std::is\_assignable](http://en.cppreference.com/w/cpp/types/is_assignable)<T2&, U2>::value` are both `true`. 8) Assigns `[std::forward](http://en.cppreference.com/w/cpp/utility/forward)<U1>(p.first)` to `first` and `[std::forward](http://en.cppreference.com/w/cpp/utility/forward)<U2>(p.second)` to `second`. * This overload participates in overload resolution only if `[std::is\_assignable\_v](http://en.cppreference.com/w/cpp/types/is_assignable)<const T1&, U1>` and `[std::is\_assignable\_v](http://en.cppreference.com/w/cpp/types/is_assignable)<const T2&, U2>` are both `true`. ### Parameters | | | | | --- | --- | --- | | other | - | pair of values to replace the contents of this pair | ### Return value `*this`. ### Exceptions 1-4) May throw implementation-defined exceptions. 5) [`noexcept`](../../language/noexcept_spec "cpp/language/noexcept spec") specification: `noexcept( [std::is\_nothrow\_move\_assignable](http://en.cppreference.com/w/cpp/types/is_move_assignable)<T1>::value && [std::is\_nothrow\_move\_assignable](http://en.cppreference.com/w/cpp/types/is_move_assignable)<T2>::value . )` 6-8) May throw implementation-defined exceptions. ### Example ``` #include <iomanip> #include <iostream> #include <utility> #include <vector> template <class Os, class T> Os& operator<<(Os& os, const std::vector<T>& v) { os << "{"; for (std::size_t t = 0; t != v.size(); ++t) os << v[t] << (t+1 < v.size() ? "," : ""); return os << "}"; } template <class Os, class U1, class U2> Os& operator<<(Os& os, const std::pair<U1, U2>& pair) { return os << ":{ " << pair.first << ", " << pair.second << " } "; } int main() { std::pair<int, std::vector<int>> p{ 1, {2} }, q{ 2, {5,6} }; p = q; // (1) operator=( const pair& other ); std::cout << std::setw(23) << std::left << "(1) p = q;" << "p" << p << " q" << q << '\n'; std::pair<short, std::vector<int>> r{ 4, {7,8,9} }; p = r; // (3) operator=( const pair<U1,U2>& other ); std::cout << std::setw(23) << "(3) p = r;" << "p" << p << " r" << r << '\n'; p = std::pair<int, std::vector<int>>{ 3, {4} }; p = std::move(q); // (5) operator=( pair&& other ); std::cout << std::setw(23) << "(5) p = std::move(q);" << "p" << p << " q" << q << '\n'; p = std::pair<int, std::vector<int>>{ 5, {6} }; p = std::move(r); // (7) operator=( pair<U1,U2>&& other ); std::cout << std::setw(23) << "(7) p = std::move(r);" << "p" << p << " r" << r << '\n'; } ``` Output: ``` (1) p = q; p:{ 2, {5,6} } q:{ 2, {5,6} } (3) p = r; p:{ 4, {7,8,9} } r:{ 4, {7,8,9} } (5) p = std::move(q); p:{ 2, {5,6} } q:{ 2, {} } (7) p = std::move(r); p:{ 4, {7,8,9} } r:{ 4, {} } ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 2729](https://cplusplus.github.io/LWG/issue2729) | C++11 | `pair::operator=` was unconstrained and mightresult in unnecessary undefined behavior | constrained | ### See also | | | | --- | --- | | [operator=](../tuple/operator= "cpp/utility/tuple/operator=") (C++11) | assigns the contents of one `tuple` to another (public member function of `std::tuple<Types...>`) |
programming_docs
cpp operator==,!=,<,<=,>,>=,<=>(std::pair) operator==,!=,<,<=,>,>=,<=>(std::pair) ====================================== | Defined in header `[<utility>](../../header/utility "cpp/header/utility")` | | | | --- | --- | --- | | | (1) | | | ``` template< class T1, class T2 > bool operator==( const std::pair<T1,T2>& lhs, const std::pair<T1,T2>& rhs ); ``` | (until C++14) | | ``` template< class T1, class T2 > constexpr bool operator==( const std::pair<T1,T2>& lhs, const std::pair<T1,T2>& rhs ); ``` | (since C++14) | | | (2) | | | ``` template< class T1, class T2 > bool operator!=( const std::pair<T1,T2>& lhs, const std::pair<T1,T2>& rhs ); ``` | (until C++14) | | ``` template< class T1, class T2 > constexpr bool operator!=( const std::pair<T1,T2>& lhs, const std::pair<T1,T2>& rhs ); ``` | (since C++14) (until C++20) | | | (3) | | | ``` template< class T1, class T2 > bool operator<( const std::pair<T1,T2>& lhs, const std::pair<T1,T2>& rhs ); ``` | (until C++14) | | ``` template< class T1, class T2 > constexpr bool operator<( const std::pair<T1,T2>& lhs, const std::pair<T1,T2>& rhs ); ``` | (since C++14) (until C++20) | | | (4) | | | ``` template< class T1, class T2 > bool operator<=( const std::pair<T1,T2>& lhs, const std::pair<T1,T2>& rhs ); ``` | (until C++14) | | ``` template< class T1, class T2 > constexpr bool operator<=( const std::pair<T1,T2>& lhs, const std::pair<T1,T2>& rhs ); ``` | (since C++14) (until C++20) | | | (5) | | | ``` template< class T1, class T2 > bool operator>( const std::pair<T1,T2>& lhs, const std::pair<T1,T2>& rhs ); ``` | (until C++14) | | ``` template< class T1, class T2 > constexpr bool operator>( const std::pair<T1,T2>& lhs, const std::pair<T1,T2>& rhs ); ``` | (since C++14) (until C++20) | | | (6) | | | ``` template< class T1, class T2 > bool operator>=( const std::pair<T1,T2>& lhs, const std::pair<T1,T2>& rhs ); ``` | (until C++14) | | ``` template< class T1, class T2 > constexpr bool operator>=( const std::pair<T1,T2>& lhs, const std::pair<T1,T2>& rhs ); ``` | (since C++14) (until C++20) | | ``` template< class T1, class T2 > constexpr /* see below */ operator<=>( const std::pair<T1,T2>& lhs, const std::pair<T1,T2>& rhs ); ``` | (7) | (since C++20) | 1-2) Tests if both elements of lhs and rhs are equal, that is, compares `lhs.first` with `rhs.first` and `lhs.second` with `rhs.second`. 3-6) Compares `lhs` and `rhs` lexicographically by `operator<`, that is, compares the first elements and only if they are equivalent, compares the second elements. 7) Compares `lhs` and `rhs` lexicographically by *synthesized three-way comparison* (see below), that is, compares the first elements and only if they are equivalent, compares the second elements. The return type is the [common comparison category type](../compare/common_comparison_category "cpp/utility/compare/common comparison category") of the result type of synthesized three-way comparison on `T1` and the one of `T2`. | | | | --- | --- | | The `<`, `<=`, `>`, `>=`, and `!=` operators are [synthesized](../../language/operators#Relational_operators "cpp/language/operators") from `operator<=>` and `operator==` respectively. | (since C++20) | | | | | --- | --- | | Synthesized three-way comparison Given an object type `T`, two `const T` lvalues `lhs` and `rhs` as left hand operand and right hand operand respectively, *synthesized three-way comparison* is defined as:* if `[std::three\_way\_comparable\_with](http://en.cppreference.com/w/cpp/utility/compare/three_way_comparable)<T, T>` is satisfied, equivalent to `lhs <=> rhs`; * otherwise, if comparing two `const T` lvalues by `operator<` is well-formed and the result type satisfies *`boolean-testable`*, equivalent to ``` lhs < rhs ? std::weak_ordering::less : rhs < lhs ? std::weak_ordering::greater : std::weak_ordering::equivalent ``` * otherwise, synthesized three-way comparison is not defined, which makes `operator<=>` not participate in overload resolution. The behavior of `operator<=>` is undefined if [`three_way_comparable_with`](../compare/three_way_comparable "cpp/utility/compare/three way comparable") or *`boolean-testable`* is satisfied but not modeled. | (since C++20) | ### Parameters | | | | | --- | --- | --- | | lhs, rhs | - | pairs to compare | ### Return value 1) `true` if both `lhs.first == rhs.first` and `lhs.second == rhs.second`, otherwise `false` 2) `!(lhs == rhs)` 3) If `lhs.first<rhs.first`, returns `true`. Otherwise, if `rhs.first<lhs.first`, returns `false`. Otherwise, if `lhs.second<rhs.second`, returns `true`. Otherwise, returns `false`. 4) `!(rhs < lhs)` 5) `rhs < lhs` 6) `!(lhs < rhs)` 7) `synth_three_way(lhs.first, rhs.first)` if it is not equal to `0`, otherwise `synth_three_way(lhs.second, rhs.second)`, where *`synth_three_way`* is an exposition-only function object performing synthesized three-way comparison. ### Example Because operator< is defined for pairs, containers of pairs can be sorted. ``` #include <iostream> #include <iomanip> #include <utility> #include <vector> #include <algorithm> #include <string> int main() { std::vector<std::pair<int, std::string>> v = { {2, "baz"}, {2, "bar"}, {1, "foo"} }; std::sort(v.begin(), v.end()); for(auto p: v) { std::cout << "{" << p.first << ", " << std::quoted(p.second) << "}\n"; } } ``` Output: ``` {1, "foo"} {2, "bar"} {2, "baz"} ``` ### See also | | | | --- | --- | | [operator==operator!=operator<operator<=operator>operator>=operator<=>](../tuple/operator_cmp "cpp/utility/tuple/operator cmp") (removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(C++20) | lexicographically compares the values in the tuple (function template) | cpp std::get(std::pair) std::get(std::pair) =================== | Defined in header `[<utility>](../../header/utility "cpp/header/utility")` | | | | --- | --- | --- | | | (1) | | | ``` template< std::size_t I, class T1, class T2 > typename std::tuple_element<I, std::pair<T1,T2> >::type& get( std::pair<T1, T2>& p ) noexcept; ``` | (since C++11) (until C++14) | | ``` template< std::size_t I, class T1, class T2 > constexpr std::tuple_element_t<I, std::pair<T1,T2> >& get( std::pair<T1, T2>& p ) noexcept; ``` | (since C++14) | | | (2) | | | ``` template< std::size_t I, class T1, class T2 > const typename std::tuple_element<I, std::pair<T1,T2> >::type& get( const std::pair<T1,T2>& p ) noexcept; ``` | (since C++11) (until C++14) | | ``` template< std::size_t I, class T1, class T2 > constexpr const std::tuple_element_t<I, std::pair<T1,T2> >& get( const std::pair<T1,T2>& p ) noexcept; ``` | (since C++14) | | | (3) | | | ``` template< std::size_t I, class T1, class T2 > typename std::tuple_element<I, std::pair<T1,T2> >::type&& get( std::pair<T1,T2>&& p ) noexcept; ``` | (since C++11) (until C++14) | | ``` template< std::size_t I, class T1, class T2 > constexpr std::tuple_element_t<I, std::pair<T1,T2> >&& get( std::pair<T1,T2>&& p ) noexcept; ``` | (since C++14) | | | (4) | | | ``` template< std::size_t I, class T1, class T2 > const typename std::tuple_element<I, std::pair<T1,T2> >::type&& get( const std::pair<T1,T2>&& p ) noexcept; ``` | (since C++11) (until C++14) | | ``` template< std::size_t I, class T1, class T2 > constexpr const std::tuple_element_t<I, std::pair<T1,T2> >&& get( const std::pair<T1,T2>&& p ) noexcept; ``` | (since C++14) | | ``` template <class T, class U> constexpr T& get(std::pair<T, U>& p) noexcept; ``` | (5) | (since C++14) | | ``` template <class T, class U> constexpr const T& get(const std::pair<T, U>& p) noexcept; ``` | (6) | (since C++14) | | ``` template <class T, class U> constexpr T&& get(std::pair<T, U>&& p) noexcept; ``` | (7) | (since C++14) | | ``` template <class T, class U> constexpr const T&& get(const std::pair<T, U>&& p) noexcept; ``` | (8) | (since C++14) | | ``` template <class T, class U> constexpr T& get(std::pair<U, T>& p) noexcept; ``` | (9) | (since C++14) | | ``` template <class T, class U> constexpr const T& get(const std::pair<U, T>& p) noexcept; ``` | (10) | (since C++14) | | ``` template <class T, class U> constexpr T&& get(std::pair<U, T>&& p) noexcept; ``` | (11) | (since C++14) | | ``` template <class T, class U> constexpr const T&& get(const std::pair<U, T>&& p) noexcept; ``` | (12) | (since C++14) | Extracts an element from the pair using tuple-like interface. The index-based overloads (1-4) fail to compile if the index `I` is neither 0 nor 1. The type-based overloads (5-12) fail to compile if the types `T` and `U` are the same. ### Parameters | | | | | --- | --- | --- | | p | - | pair whose contents to extract | ### Return value 1-4) Returns a reference to `p.first` if `I==0` and a reference to `p.second` if `I==1`. 5-8) Returns a reference to `p.first`. 9-12) Returns a reference to `p.second`. ### Example ``` #include <iostream> #include <utility> int main() { auto p = std::make_pair(1, 3.14); std::cout << '(' << std::get<0>(p) << ", " << std::get<1>(p) << ")\n"; std::cout << '(' << std::get<int>(p) << ", " << std::get<double>(p) << ")\n"; } ``` Output: ``` (1, 3.14) (1, 3.14) ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 2485](https://cplusplus.github.io/LWG/issue2485) | C++11 (by index)C++14 (by type) | there are no overloads for const pair&& | the overloads are added | ### See also | | | | --- | --- | | [Structured binding](../../language/structured_binding "cpp/language/structured binding") (C++17) | binds the specified names to sub-objects or tuple elements of the initializer | | [std::get(std::tuple)](../tuple/get "cpp/utility/tuple/get") (C++11) | tuple accesses specified element (function template) | | [std::get(std::array)](../../container/array/get "cpp/container/array/get") (C++11) | accesses an element of an `array` (function template) | | [std::get(std::variant)](../variant/get "cpp/utility/variant/get") (C++17) | reads the value of the variant given the index or the type (if the type is unique), throws on error (function template) | | [get(std::ranges::subrange)](../../ranges/subrange/get "cpp/ranges/subrange/get") (C++20) | obtains iterator or sentinel from a `[std::ranges::subrange](../../ranges/subrange "cpp/ranges/subrange")` (function template) | eslint Getting Started with ESLint Getting Started with ESLint =========================== ESLint is a tool for identifying and reporting on patterns found in ECMAScript/JavaScript code, with the goal of making code more consistent and avoiding bugs. In many ways, it is similar to JSLint and JSHint with a few exceptions: * ESLint uses [Espree](https://github.com/eslint/espree) for JavaScript parsing. * ESLint uses an AST to evaluate patterns in code. * ESLint is completely pluggable, every single rule is a plugin and you can add more at runtime. Installation and Usage ---------------------- Prerequisites: [Node.js](https://nodejs.org/en/) (`^12.22.0`, `^14.17.0`, or `>=16.0.0`) built with SSL support. (If you are using an official Node.js distribution, SSL is always built in.) You can install and configure ESLint using this command: ``` npm init @eslint/config ``` If you want to use a specific shareable config that is hosted on npm, you can use the `--config` option and specify the package name: ``` # use `eslint-config-semistandard` shared config # npm 6.x npm init @eslint/config --config semistandard # ⚠️ npm 7+, extra double-dash is needed: npm init @eslint/config -- --config semistandard # or (`eslint-config` prefix is optional) npm init @eslint/config -- --config eslint-config-semistandard ``` The `--config` flag also supports passing in arrays: ``` npm init @eslint/config -- --config semistandard,standard # or npm init @eslint/config -- --config semistandard --config standard ``` **Note:** `npm init @eslint/config` assumes you have a `package.json` file already. If you don’t, make sure to run `npm init` or `yarn init` beforehand. After that, you can run ESLint on any file or directory like this: ``` npx eslint yourfile.js # or yarn run eslint yourfile.js ``` It is also possible to install ESLint globally rather than locally (using `npm install eslint --global`). However, this is not recommended, and any plugins or shareable configs that you use must be installed locally in either case. Configuration ------------- **Note:** If you are coming from a version before 1.0.0 please see the [migration guide](user-guide/getting-startedmigrating-to-1.0.0). After running `npm init @eslint/config`, you’ll have a `.eslintrc.{js,yml,json}` file in your directory. In it, you’ll see some rules configured like this: ``` { "rules": { "semi": ["error", "always"], "quotes": ["error", "double"] } } ``` The names `"semi"` and `"quotes"` are the names of [rules](user-guide/getting-started../rules) in ESLint. The first value is the error level of the rule and can be one of these values: * `"off"` or `0` - turn the rule off * `"warn"` or `1` - turn the rule on as a warning (doesn’t affect exit code) * `"error"` or `2` - turn the rule on as an error (exit code will be 1) The three error levels allow you fine-grained control over how ESLint applies rules (for more configuration options and details, see the [configuration docs](user-guide/getting-startedconfiguring/index)). Your `.eslintrc.{js,yml,json}` configuration file will also include the line: ``` { "extends": "eslint:recommended" } ``` Because of this line, all of the rules marked “(recommended)” on the [rules page](user-guide/getting-started../rules) will be turned on. Alternatively, you can use configurations that others have created by searching for “eslint-config” on [npmjs.com](https://www.npmjs.com/search?q=eslint-config). ESLint will not lint your code unless you extend from a shared configuration or explicitly turn rules on in your configuration. Next Steps ---------- * Learn about [advanced configuration](user-guide/getting-startedconfiguring/index) of ESLint. * Get familiar with the [command line options](user-guide/getting-startedcommand-line-interface). * Explore [ESLint integrations](user-guide/getting-startedintegrations) into other tools like editors, build systems, and more. * Can’t find just the right rule? Make your own [custom rule](user-guide/getting-started../developer-guide/working-with-rules). * Make ESLint even better by [contributing](user-guide/getting-started../developer-guide/contributing/index). eslint Migrating to v1.0.0 Migrating to v1.0.0 =================== ESLint v1.0.0 is the first major version release. As a result, there are some significant changes between how ESLint worked during its life in 0.x and how it will work going forward. These changes are the direct result of feedback from the ESLint community of users and were not made without due consideration for the upgrade path. We believe that these changes make ESLint even better, and while some work is necessary to upgrade, we hope the pain of this upgrade is small enough that you will see the benefit of upgrading. All Rules Off by Default ------------------------ The most important difference in v1.0.0 is that all rules are off by default. We made this change after numerous requests to allow turning off the default rules from within configuration files. While that wasn’t technically feasible, it was feasible to have all rules off by default and then re-enable rules in configuration files using `extends`. As such, we’ve made the `--reset` behavior the default and removed this command line option. When using `--init`, your configuration file will automatically include the following line: ``` { "extends": "eslint:recommended" } ``` This setting mimics some of the default behavior from 0.x, but not all. If you don’t want to use any of the recommended rules, you can delete this line. **To address:** If you are currently using `--reset`, then you should stop passing `--reset` on the command line; no other changes are necessary. If you are not using `--reset`, then you should review your configuration to determine which rules should be on by default. You can partially restore some of the default behavior by adding the following to your configuration file: The `"eslint:recommended"` configuration contains many of the same default rule settings from 0.x, but not all. These rules are no longer on by default, so you should review your settings to ensure they are still as you expect: * [no-alert](migrating-to-1.0.0../rules/no-alert) * [no-array-constructor](migrating-to-1.0.0../rules/no-array-constructor) * [no-caller](migrating-to-1.0.0../rules/no-caller) * [no-catch-shadow](migrating-to-1.0.0../rules/no-catch-shadow) * [no-empty-label](migrating-to-1.0.0../rules/no-empty-label) * [no-eval](migrating-to-1.0.0../rules/no-eval) * [no-extend-native](migrating-to-1.0.0../rules/no-extend-native) * [no-extra-bind](migrating-to-1.0.0../rules/no-extra-bind) * [no-extra-strict](migrating-to-1.0.0../rules/no-extra-strict) * [no-implied-eval](migrating-to-1.0.0../rules/no-implied-eval) * [no-iterator](migrating-to-1.0.0../rules/no-iterator) * [no-label-var](migrating-to-1.0.0../rules/no-label-var) * [no-labels](migrating-to-1.0.0../rules/no-labels) * [no-lone-blocks](migrating-to-1.0.0../rules/no-lone-blocks) * [no-loop-func](migrating-to-1.0.0../rules/no-loop-func) * [no-multi-spaces](migrating-to-1.0.0../rules/no-multi-spaces) * [no-multi-str](migrating-to-1.0.0../rules/no-multi-str) * [no-native-reassign](migrating-to-1.0.0../rules/no-native-reassign) * [no-new](migrating-to-1.0.0../rules/no-new) * [no-new-func](migrating-to-1.0.0../rules/no-new-func) * [no-new-object](migrating-to-1.0.0../rules/no-new-object) * [no-new-wrappers](migrating-to-1.0.0../rules/no-new-wrappers) * [no-octal-escape](migrating-to-1.0.0../rules/no-octal-escape) * [no-process-exit](migrating-to-1.0.0../rules/no-process-exit) * [no-proto](migrating-to-1.0.0../rules/no-proto) * [no-return-assign](migrating-to-1.0.0../rules/no-return-assign) * [no-script-url](migrating-to-1.0.0../rules/no-script-url) * [no-sequences](migrating-to-1.0.0../rules/no-sequences) * [no-shadow](migrating-to-1.0.0../rules/no-shadow) * [no-shadow-restricted-names](migrating-to-1.0.0../rules/no-shadow-restricted-names) * [no-spaced-func](migrating-to-1.0.0../rules/no-spaced-func) * [no-trailing-spaces](migrating-to-1.0.0../rules/no-trailing-spaces) * [no-undef-init](migrating-to-1.0.0../rules/no-undef-init) * [no-underscore-dangle](migrating-to-1.0.0../rules/no-underscore-dangle) * [no-unused-expressions](migrating-to-1.0.0../rules/no-unused-expressions) * [no-use-before-define](migrating-to-1.0.0../rules/no-use-before-define) * [no-with](migrating-to-1.0.0../rules/no-with) * [no-wrap-func](migrating-to-1.0.0../rules/no-wrap-func) * [camelcase](migrating-to-1.0.0../rules/camelcase) * [comma-spacing](migrating-to-1.0.0../rules/comma-spacing) * [consistent-return](migrating-to-1.0.0../rules/consistent-return) * [curly](migrating-to-1.0.0../rules/curly) * [dot-notation](migrating-to-1.0.0../rules/dot-notation) * [eol-last](migrating-to-1.0.0../rules/eol-last) * [eqeqeq](migrating-to-1.0.0../rules/eqeqeq) * [key-spacing](migrating-to-1.0.0../rules/key-spacing) * [new-cap](migrating-to-1.0.0../rules/new-cap) * [new-parens](migrating-to-1.0.0../rules/new-parens) * [quotes](migrating-to-1.0.0../rules/quotes) * [semi](migrating-to-1.0.0../rules/semi) * [semi-spacing](migrating-to-1.0.0../rules/semi-spacing) * [space-infix-ops](migrating-to-1.0.0../rules/space-infix-ops) * [space-return-throw-case](migrating-to-1.0.0../rules/space-return-throw-case) * [space-unary-ops](migrating-to-1.0.0../rules/space-unary-ops) * [strict](migrating-to-1.0.0../rules/strict) * [yoda](migrating-to-1.0.0../rules/yoda) See also: the [full diff](https://github.com/eslint/eslint/commit/e3e9dbd9876daf4bdeb4e15f8a76a9d5e6e03e39#diff-b01a5cfd9361ca9280a460fd6bb8edbbL1) where the defaults were changed. Here’s a configuration file with the closest equivalent of the old defaults: ``` { "extends": "eslint:recommended", "rules": { "no-alert": 2, "no-array-constructor": 2, "no-caller": 2, "no-catch-shadow": 2, "no-empty-label": 2, "no-eval": 2, "no-extend-native": 2, "no-extra-bind": 2, "no-implied-eval": 2, "no-iterator": 2, "no-label-var": 2, "no-labels": 2, "no-lone-blocks": 2, "no-loop-func": 2, "no-multi-spaces": 2, "no-multi-str": 2, "no-native-reassign": 2, "no-new": 2, "no-new-func": 2, "no-new-object": 2, "no-new-wrappers": 2, "no-octal-escape": 2, "no-process-exit": 2, "no-proto": 2, "no-return-assign": 2, "no-script-url": 2, "no-sequences": 2, "no-shadow": 2, "no-shadow-restricted-names": 2, "no-spaced-func": 2, "no-trailing-spaces": 2, "no-undef-init": 2, "no-underscore-dangle": 2, "no-unused-expressions": 2, "no-use-before-define": 2, "no-with": 2, "camelcase": 2, "comma-spacing": 2, "consistent-return": 2, "curly": [2, "all"], "dot-notation": [2, { "allowKeywords": true }], "eol-last": 2, "no-extra-parens": [2, "functions"], "eqeqeq": 2, "key-spacing": [2, { "beforeColon": false, "afterColon": true }], "new-cap": 2, "new-parens": 2, "quotes": [2, "double"], "semi": 2, "semi-spacing": [2, {"before": false, "after": true}], "space-infix-ops": 2, "space-return-throw-case": 2, "space-unary-ops": [2, { "words": true, "nonwords": false }], "strict": [2, "function"], "yoda": [2, "never"] } } ``` Removed Rules ------------- Over the past several releases, we have been deprecating rules and introducing new rules to take their place. The following is a list of the removed rules and their replacements: * [generator-star](migrating-to-1.0.0../rules/generator-star) is replaced by [generator-star-spacing](migrating-to-1.0.0../rules/generator-star-spacing) * [global-strict](migrating-to-1.0.0../rules/global-strict) is replaced by [strict](migrating-to-1.0.0../rules/strict) * [no-comma-dangle](migrating-to-1.0.0../rules/no-comma-dangle) is replaced by [comma-dangle](migrating-to-1.0.0../rules/comma-dangle) * [no-empty-class](migrating-to-1.0.0../rules/no-empty-class) is replaced by [no-empty-character-class](migrating-to-1.0.0../rules/no-empty-character-class) * [no-extra-strict](migrating-to-1.0.0../rules/no-extra-strict) is replaced by [strict](migrating-to-1.0.0../rules/strict) * [no-reserved-keys](migrating-to-1.0.0../rules/no-reserved-keys) is replaced by [quote-props](migrating-to-1.0.0../rules/quote-props) * [no-space-before-semi](migrating-to-1.0.0../rules/no-space-before-semi) is replaced by [semi-spacing](migrating-to-1.0.0../rules/semi-spacing) * [no-wrap-func](migrating-to-1.0.0../rules/no-wrap-func) is replaced by [no-extra-parens](migrating-to-1.0.0../rules/no-extra-parens) * [space-after-function-name](migrating-to-1.0.0../rules/space-after-function-name) is replaced by [space-before-function-paren](migrating-to-1.0.0../rules/space-before-function-paren) * [space-before-function-parentheses](migrating-to-1.0.0../rules/space-before-function-parentheses) is replaced by [space-before-function-paren](migrating-to-1.0.0../rules/space-before-function-paren) * [space-in-brackets](migrating-to-1.0.0../rules/space-in-brackets) is replaced by[object-curly-spacing](migrating-to-1.0.0../rules/object-curly-spacing) and [array-bracket-spacing](migrating-to-1.0.0../rules/array-bracket-spacing) * [space-unary-word-ops](migrating-to-1.0.0../rules/space-unary-word-ops) is replaced by [space-unary-ops](migrating-to-1.0.0../rules/space-unary-ops) * [spaced-line-comment](migrating-to-1.0.0../rules/spaced-line-comment) is replaced by [spaced-comment](migrating-to-1.0.0../rules/spaced-comment) **To address:** You’ll need to update your rule configurations to use the new rules. ESLint v1.0.0 will also warn you when you’re using a rule that has been removed and will suggest the replacement rules. Hopefully, this will result in few surprises during the upgrade process. Column Numbers are 1-based -------------------------- From the beginning, ESLint has reported errors using 0-based columns because that’s what Esprima, and later Espree, reported. However, most tools and editors use 1-based columns, which made for some tricky integrations with ESLint. In v1.0.0, we’ve switched over to reporting errors using 1-based columns to fall into line with the tools developers use everyday. **To address:** If you’ve created an editor integration, or a tool that had to correct the column number, you’ll need to update to just pass through the column number from ESLint. Otherwise, no change is necessary. No Longer Exporting cli ----------------------- In 0.x, the `cli` object was exported for use by external tools. It was later deprecated in favor of `CLIEngine`. In v1.0.0, we are no longer exporting `cli` as it should not be used by external tools. This will break existing tools that make use of it. **To address:** If you are using the exported `cli` object, switch to using `CLIEngine` instead. Deprecating eslint-tester ------------------------- The `eslint-tester` module, which has long been the primary tester for ESLint rules, has now been moved into the `eslint` module. This was the result of a difficult relationship between these two modules that created circular dependencies and was causing a lot of problems in rule tests. Moving the tester into the `eslint` module fixed a lot of those issues. The replacement for `eslint-tester` is called `RuleTester`. It’s a simplified version of `ESLintTester` that’s designed to work with any testing framework. This object is exposed by the package. **To address:** Convert all of your rule tests to use `RuleTester`. If you have this as a test using `ESLintTester`: ``` var eslint = require("../../../lib/eslint"), ESLintTester = require("eslint-tester"); var eslintTester = new ESLintTester(eslint); eslintTester.addRuleTest("lib/rules/your-rule", { valid: [], invalid: [] }); ``` Then you can change to: ``` var rule = require("../../../lib/rules/your-rule"), RuleTester = require("eslint").RuleTester; var ruleTester = new RuleTester(); ruleTester.run("your-rule", rule, { valid: [], invalid: [] }); ```
programming_docs
eslint User Guide User Guide ========== This guide is intended for those who wish to use ESLint as an end-user. If you’re looking for how to extend ESLint or work with the ESLint source code, please see the [Developer Guide](../developer-guide/index). [Getting Started](../index) --------------------------- Want to skip ahead and just start using ESLint? This section gives a high-level overview of installation, setup, and configuration options. [Rules](../rules/index) ----------------------- ESLint has a lot of rules that you can configure to fine-tune it to your project. This section is an exhaustive list of every rule and link to each rule’s documentation. [Configuring](configuring/index) -------------------------------- Once you’ve got ESLint running, you’ll probably want to adjust the configuration to better suit your project. This section explains all the different ways you can configure ESLint. [Command Line Interface](command-line-interface) ------------------------------------------------ There are a lot of command line flags for ESLint and this section explains what they do. [Integrations](integrations) ---------------------------- Wondering if ESLint will work with your favorite editor or build system? This section has a list of all known integrations (submitted by their authors). [Rule Deprecation](rule-deprecation) ------------------------------------ The ESLint team is committed to making upgrading as easy and painless as possible. This section outlines the guidelines the team has set in place for the deprecation of rules in future releases. Migrating --------- If you were using a prior version of ESLint, you can get help with the transition by reading: * <migrating-to-1.0.0> * <migrating-to-2.0.0> * <migrating-to-3.0.0> * <migrating-to-4.0.0> * <migrating-to-5.0.0> * <migrating-to-6.0.0> * <migrating-to-7.0.0> * <migrating-to-8.0.0> eslint Core Concepts Core Concepts ============= This page contains a high-level overview of some of the core concepts of ESLint. What is ESLint? --------------- ESLint is a configurable JavaScript linter. It helps you find and fix problems in your JavaScript code. Problems can be anything from potential runtime bugs, to not following best practices, to styling issues. Rules ----- Rules are the core building block of ESLint. A rule validates if your code meets a certain expectation, and what to do if it does not meet that expectation. Rules can also contain additional configuration options specific to that rule. For example, the [`semi`](core-concepts../rules/semi) rule lets you specify whether or not JavaScript statements should end with a semicolon (`;`). You can set the rule to either always require semicolons or require that a statement never ends with a semicolon. ESLint contains hundreds of built-in rules that you can use. You can also create custom rules or use rules that others have created with [plugins](#plugins). For more information, refer to [Rules](core-concepts../rules/index). Configuration Files ------------------- An ESLint configuration file is a place where you put the configuration for ESLint in your project. You can include built-in rules, how you want them enforced, plugins with custom rules, shareable configurations, which files you want rules to apply to, and more. For more information, refer to [Configuration Files](core-concepts./configuring/configuration-files). Shareable Configurations ------------------------ Shareable configurations are ESLint configurations that are shared via npm. Often shareable configurations are used to enforce style guides using ESLint’s built-in rules. For example the sharable configuration [eslint-config-airbnb-base](https://www.npmjs.com/package/eslint-config-airbnb-base) implements the popular Airbnb JavaScript style guide. For more information, refer to [Using a shareable configuration package](core-concepts./configuring/configuration-files#using-a-shareable-configuration-package). Plugins ------- An ESLint plugin is an npm module that can contain a set of ESLint rules, configurations, processors, and environments. Often plugins include custom rules. Plugins can be used to enforce a style guide and support JavaScript extensions (like TypeScript), libraries (like React), and frameworks (Angular). A popular use case for plugins is to enforce best practices for a framework. For example, [@angular-eslint/eslint-plugin](https://www.npmjs.com/package/@angular-eslint/eslint-plugin) contains best practices for using the Angular framework. For more information, refer to [Configuring Plugins](core-concepts./configuring/plugins). Parsers ------- An ESLint parser converts code into an abstract syntax tree that ESLint can evaluate. By default, ESLint uses the built-in [Espree](https://github.com/eslint/espree) parser, which is compatible with standard JavaScript runtimes and versions. Custom parsers let ESLint parse non-standard JavaScript syntax. Often custom parsers are included as part of shareable configurations or plugins, so you don’t have to use them directly. For example, [@typescript-eslint/parser](core-conceptsnpmjs.com/package/@typescript-eslint/parser) is a custom parser included in the [typescript-eslint](https://github.com/typescript-eslint/typescript-eslint) project that lets ESLint parse TypeScript code. Custom Processors ----------------- An ESLint processor extracts JavaScript code from other kinds of files, then lets ESLint lint the JavaScript code. Alternatively, you can use a processor to manipulate JavaScript code before parsing it with ESLint. For example, [eslint-plugin-markdown](https://github.com/eslint/eslint-plugin-markdown) contains a custom processor that lets you lint JavaScript code inside of Markdown code blocks. Formatters ---------- An ESLint formatter controls the appearance of the linting results in the CLI. For more information, refer to [Formatters](core-concepts./formatters/index). Integrations ------------ One of the things that makes ESLint such a useful tool is the ecosystem of integrations that surrounds it. For example, many code editors have ESLint extensions that show you the ESLint results of your code in the file as you work so that you don’t need to use the ESLint CLI to see linting results. For more information, refer to [Integrations](core-concepts./integrations). CLI & Node.js API ----------------- The ESLint CLI is a command line interface that lets you execute linting from the terminal. The CLI has a variety of options that you can pass to its commands. The ESLint Node.js API lets you use ESLint programmatically from Node.js code. The API is useful when developing plugins, integrations, and other tools related to ESLint. Unless you are extending ESLint in some way, you should use the CLI. For more information, refer to [Command Line Interface](core-concepts./command-line-interface) and [Node.js API](core-concepts../developer-guide/nodejs-api). eslint Migrating to v7.0.0 Migrating to v7.0.0 =================== ESLint v7.0.0 is a major release of ESLint. We have made a few breaking changes in this release. This guide is intended to walk you through the breaking changes. The lists below are ordered roughly by the number of users each change is expected to affect, where the first items are expected to affect the most users. Table of Content ---------------- ### Breaking changes for users * [Node.js 8 is no longer supported](#drop-node-8) * [Lint files matched by `overrides[].files` by default](#additional-lint-targets) * [The base path of `overrides` and `ignorePatterns` is changed if the config file is given by the `--config`/`--ignore-path` options](#base-path-change) * [The place where ESLint loads plugins from is changed](#plugin-loading-change) * [Runtime deprecation warnings for `~/.eslintrc.*` config files](#runtime-deprecation-on-personal-config-files) * [Default ignore patterns have changed](#default-ignore-patterns) * [Description in directive comments](#description-in-directive-comments) * [Node.js/CommonJS rules are deprecated](#deprecate-node-rules) * [Several rules have been updated to cover more cases](#rules-strict) * [`eslint:recommended` has been updated](#eslint-recommended) ### Breaking changes for plugin developers * [Node.js 8 is no longer supported](#drop-node-8) * [Lint files matched by `overrides[].files` by default](#additional-lint-targets) * [Plugin resolution has been updated](#plugin-loading-change) * [Additional validation added to the `RuleTester` class](#rule-tester-strict) ### Breaking changes for integration developers * [Node.js 8 is no longer supported](#drop-node-8) * [Plugin resolution has been updated](#plugin-loading-change) * [The `CLIEngine` class has been deprecated](#deprecate-cliengine) Node.js 8 is no longer supported ---------------------------------- Node.js 8 reached EOL in December 2019, and we are officially dropping support for it in this release. ESLint now supports the following versions of Node.js: * Node.js 10 (`10.12.0` and above) * Node.js 12 and above **To address:** Make sure you upgrade to at least Node.js `10.12.0` when using ESLint v7.0.0. One important thing to double check is the Node.js version supported by your editor when using ESLint via editor integrations. If you are unable to upgrade, we recommend continuing to use ESLint 6 until you are able to upgrade Node.js. **Related issue(s):** [RFC44](https://github.com/eslint/rfcs/blob/master/designs/2019-drop-node8/README.md), [#12700](https://github.com/eslint/eslint/pull/12700) Lint files matched by `overrides[].files` by default ------------------------------------------------------ Previously to v7.0.0, ESLint would only lint files with a `.js` extension by default if you give directories like `eslint src`. ESLint v7.0.0 will now additionally lint files with other extensions (`.ts`, `.vue`, etc.) if the extension is explicitly matched by an `overrides[].files` entry. This will allow for users to lint files that don’t end with `*.js` to be linted without having to use the `--ext` command line flag, as well as allow shared configuration authors to enable linting of these files without additional overhead for the end user. Please note that patterns that end with `*` are exempt from this behavior and will behave as they did previously. For example, if the following config file is present, ``` # .eslintrc.yml extends: my-config-js overrides: - files: "\*.ts" extends: my-config-ts ``` then running `eslint src` would check both `*.js` and `*.ts` files in the `src` directory. **To address:** Using the `--ext` CLI option will override this new behavior. Run ESLint with `--ext .js` if you are using `overrides` but only want to lint files that have a `.js` extension. If you maintain plugins that check files with extensions other than `.js`, this feature will allow you to check these files by default by configuring an `overrides` setting in your `recommended` preset. **Related issue(s):** [RFC20](https://github.com/eslint/rfcs/blob/master/designs/2019-additional-lint-targets/README.md), [#12677](https://github.com/eslint/eslint/pull/12677) The base path of `overrides` and `ignorePatterns` has changed when using the `--config`/`--ignore-path` options ----------------------------------------------------------------------------------------------------------------- Up until now, ESLint has resolved the following paths relative to the directory path of the *entry* configuration file: * Configuration files (`.eslintrc.*`) + relative paths in the `overrides[].files` setting + relative paths in the `overrides[].excludedFiles` setting + paths which start with `/` in the `ignorePatterns` setting * Ignore files (`.eslintignore`) + paths which start with `/` Starting in ESLint v7.0.0, configuration files and ignore files passed to ESLint using the `--config path/to/a-config` and `--ignore-path path/to/a-ignore` CLI flags, respectively, will resolve from the current working directory rather than the file location. This allows for users to utilize shared plugins without having to install them directly in their project. **To address:** Update the affected paths if you are using a configuration or ignore file via the `--config` or `--ignore-path` CLI options. **Related issue(s):** [RFC37](https://github.com/eslint/rfcs/blob/master/designs/2019-changing-base-path-in-config-files-that-cli-options-specify/README.md), [#12887](https://github.com/eslint/eslint/pull/12887) Plugin resolution has been updated ------------------------------------ In previous versions, ESLint resolved all plugins from the current working directory by default. Starting in ESLint v7.0.0, `plugins` are resolved relative to the directory path of the *entry* configuration file. This will not change anything in most cases. If a configuration file in a subdirectory has `plugins` defined, the plugins will be loaded from the subdirectory (or ancestor directories that include the current working directory if not found). This means that if you are using a config file from a shared location via `--config` option, the plugins that the config file declare will be loaded from the shared config file location. **To address:** Ensure that plugins are installed in a place that can be resolved relative to your configuration file or use `--resolve-plugins-relative-to .` to override this change. **Related issue(s):** [RFC47](https://github.com/eslint/rfcs/blob/master/designs/2019-plugin-loading-improvement/README.md), [#12922](https://github.com/eslint/eslint/pull/12922) Runtime deprecation warnings for `~/.eslintrc.*` config files --------------------------------------------------------------- Personal config files have been deprecated since [v6.7.0](https://eslint.org/blog/2019/11/eslint-v6.7.0-released). ESLint v7.0.0 will start printing runtime deprecation warnings. It will print a warning for the following situations: 1. When a project does not have a configuration file present and ESLint loads configuration from `~/.eslintrc.*`. 2. When a project has a configuration file and ESLint ignored a `~/.eslintrc.*` configuration file. This occurs when the `$HOME` directory is an ancestor directory of the project and the project’s configuration files doesn’t contain `root:true`. **To address:** Remove `~/.eslintrc.*` configuration files and add a `.eslintrc.*` configuration file to your project. Alternatively, use the `--config` option to use shared config files. **Related issue(s):** [RFC32](https://github.com/eslint/rfcs/tree/master/designs/2019-deprecating-personal-config/README.md), [#12678](https://github.com/eslint/eslint/pull/12678) Default ignore patterns have changed -------------------------------------- Up until now, ESLint has ignored the following files by default: * Dotfiles (`.*`) * `node_modules` in the current working directory (`/node_modules/*`) * `bower_components` in the current working directory (`/bower_components/*`) ESLint v7.0.0 ignores `node_modules/*` of subdirectories as well, but no longer ignores `bower_components/*` and `.eslintrc.js`. Therefore, the new default ignore patterns are: * Dotfiles except `.eslintrc.*` (`.*` but not `.eslintrc.*`) * `node_modules` (`/**/node_modules/*`) **To address:** Modify your `.eslintignore` or the `ignorePatterns` property of your config file if you don’t want to lint `bower_components/*` and `.eslintrc.js`. **Related issue(s):** [RFC51](https://github.com/eslint/rfcs/blob/master/designs/2019-update-default-ignore-patterns/README.md), [#12888](https://github.com/eslint/eslint/pull/12888) Descriptions in directive comments ------------------------------------ In older version of ESLint, there was no convenient way to indicate why a directive comment – such as `/*eslint-disable*/` – was necessary. To allow for the colocation of comments that provide context with the directive, ESLint v7.0.0 adds the ability to append arbitrary text in directive comments by ignoring text following `--` surrounded by whitespace. For example: ``` // eslint-disable-next-line a-rule, another-rule -- those are buggy!! ``` **To address:** If you have `--` surrounded by whitespace in directive comments, consider moving it into your configuration file. **Related issue(s):** [RFC33](https://github.com/eslint/rfcs/blob/master/designs/2019-description-in-directive-comments/README.md), [#12699](https://github.com/eslint/eslint/pull/12699) Node.js/CommonJS rules have been deprecated --------------------------------------------- The ten Node.js/CommonJS rules in core have been deprecated and moved to the [eslint-plugin-node](https://github.com/mysticatea/eslint-plugin-node) plugin. **To address:** As per [our deprecation policy](migrating-to-7.0.0../user-guide/rule-deprecation), the deprecated rules will remain in core for the foreseeable future and are still available for use. However, we will no longer be updating or fixing any bugs in those rules. To use a supported version of the rules, we recommend using the corresponding rules in the plugin instead. | Deprecated Rules | Replacement | | --- | --- | | [callback-return](migrating-to-7.0.0../rules/callback-return) | [node/callback-return](https://github.com/mysticatea/eslint-plugin-node/blob/v11.1.0/docs/rules/callback-return.md) | | [global-require](migrating-to-7.0.0../rules/global-require) | [node/global-require](https://github.com/mysticatea/eslint-plugin-node/blob/v11.1.0/docs/rules/global-require.md) | | [handle-callback-err](migrating-to-7.0.0../rules/handle-callback-err) | [node/handle-callback-err](https://github.com/mysticatea/eslint-plugin-node/blob/v11.1.0/docs/rules/handle-callback-err.md) | | [no-mixed-requires](migrating-to-7.0.0../rules/no-mixed-requires) | [node/no-mixed-requires](https://github.com/mysticatea/eslint-plugin-node/blob/v11.1.0/docs/rules/no-mixed-requires.md) | | [no-new-require](migrating-to-7.0.0../rules/no-new-require) | [node/no-new-require](https://github.com/mysticatea/eslint-plugin-node/blob/v11.1.0/docs/rules/no-new-require.md) | | [no-path-concat](migrating-to-7.0.0../rules/no-path-concat) | [node/no-path-concat](https://github.com/mysticatea/eslint-plugin-node/blob/v11.1.0/docs/rules/no-path-concat.md) | | [no-process-env](migrating-to-7.0.0../rules/no-process-env) | [node/no-process-env](https://github.com/mysticatea/eslint-plugin-node/blob/v11.1.0/docs/rules/no-process-env.md) | | [no-process-exit](migrating-to-7.0.0../rules/no-process-exit) | [node/no-process-exit](https://github.com/mysticatea/eslint-plugin-node/blob/v11.1.0/docs/rules/no-process-exit.md) | | [no-restricted-modules](migrating-to-7.0.0../rules/no-restricted-modules) | [node/no-restricted-require](https://github.com/mysticatea/eslint-plugin-node/blob/v11.1.0/docs/rules/no-restricted-require.md) | | [no-sync](migrating-to-7.0.0../rules/no-sync) | [node/no-sync](https://github.com/mysticatea/eslint-plugin-node/blob/v11.1.0/docs/rules/no-sync.md) | **Related issue(s):** [#12898](https://github.com/eslint/eslint/pull/12898) Several rules have been updated to cover more cases ----------------------------------------------------- Several rules have been enhanced and now report additional errors: * [accessor-pairs](migrating-to-7.0.0../rules/accessor-pairs) rule now recognizes class members by default. * [array-callback-return](migrating-to-7.0.0../rules/array-callback-return) rule now recognizes `flatMap` method. * [computed-property-spacing](migrating-to-7.0.0../rules/computed-property-spacing) rule now recognizes class members by default. * [func-names](migrating-to-7.0.0../rules/func-names) rule now recognizes function declarations in default exports. * [no-extra-parens](migrating-to-7.0.0../rules/no-extra-parens) rule now recognizes parentheses in assignment targets. * [no-dupe-class-members](migrating-to-7.0.0../rules/no-dupe-class-members) rule now recognizes computed keys for static class members. * [no-magic-numbers](migrating-to-7.0.0../rules/no-magic-numbers) rule now recognizes bigint literals. * [radix](migrating-to-7.0.0../rules/radix) rule now recognizes invalid numbers for the second parameter of `parseInt()`. * [use-isnan](migrating-to-7.0.0../rules/use-isnan) rule now recognizes class members by default. * [yoda](migrating-to-7.0.0../rules/yoda) rule now recognizes bigint literals. **To address:** Fix errors or disable these rules. **Related issue(s):** [#12490](https://github.com/eslint/eslint/pull/12490), [#12608](https://github.com/eslint/eslint/pull/12608), [#12670](https://github.com/eslint/eslint/pull/12670), [#12701](https://github.com/eslint/eslint/pull/12701), [#12765](https://github.com/eslint/eslint/pull/12765), [#12837](https://github.com/eslint/eslint/pull/12837), [#12913](https://github.com/eslint/eslint/pull/12913), [#12915](https://github.com/eslint/eslint/pull/12915), [#12919](https://github.com/eslint/eslint/pull/12919) `eslint:recommended` has been updated -------------------------------------- Three new rules have been enabled in the `eslint:recommended` preset. * [no-dupe-else-if](migrating-to-7.0.0../rules/no-dupe-else-if) * [no-import-assign](migrating-to-7.0.0../rules/no-import-assign) * [no-setter-return](migrating-to-7.0.0../rules/no-setter-return) **To address:** Fix errors or disable these rules. **Related issue(s):** [#12920](https://github.com/eslint/eslint/pull/12920) Additional validation added to the `RuleTester` class ------------------------------------------------------- The `RuleTester` now validates the following: * It fails test cases if the rule under test uses the non-standard `node.start` or `node.end` properties. Rules should use `node.range` instead. * It fails test cases if the rule under test provides an autofix but a test case doesn’t have an `output` property. Add an `output` property to test cases to test the rule’s autofix functionality. * It fails test cases if any unknown properties are found in the objects in the `errors` property. **To address:** Modify your rule or test case if existing test cases fail. **Related issue(s):** [RFC25](https://github.com/eslint/rfcs/blob/master/designs/2019-rule-tester-improvements/README.md), [#12096](https://github.com/eslint/eslint/pull/12096), [#12955](https://github.com/eslint/eslint/pull/12955) The `CLIEngine` class has been deprecated ------------------------------------------- The [`CLIEngine` class](migrating-to-7.0.0../developer-guide/nodejs-api#cliengine) has been deprecated and replaced by the new [`ESLint` class](migrating-to-7.0.0../developer-guide/nodejs-api#eslint-class). The `CLIEngine` class provides a synchronous API that is blocking the implementation of features such as parallel linting, supporting ES modules in shareable configs/parsers/plugins/formatters, and adding the ability to visually display the progress of linting runs. The new `ESLint` class provides an asynchronous API that ESLint core will now using going forward. `CLIEngine` will remain in core for the foreseeable future but may be removed in a future major version. **To address:** Update your code to use the new `ESLint` class if you are currently using `CLIEngine`. The following table maps the existing `CLIEngine` methods to their `ESLint` counterparts: | `CLIEngine` | `ESLint` | | --- | --- | | `executeOnFiles(patterns)` | `lintFiles(patterns)` | | `executeOnText(text, filePath, warnIgnored)` | `lintText(text, options)` | | `getFormatter(name)` | `loadFormatter(name)` | | `getConfigForFile(filePath)` | `calculateConfigForFile(filePath)` | | `isPathIgnored(filePath)` | `isPathIgnored(filePath)` | | `static outputFixes(results)` | `static outputFixes(results)` | | `static getErrorResults(results)` | `static getErrorResults(results)` | | `static getFormatter(name)` | (removed ※1) | | `addPlugin(pluginId, definition)` | the `plugins` constructor option | | `getRules()` | (not implemented yet) | | `resolveFileGlobPatterns()` | (removed ※2) | * ※1 The `engine.getFormatter()` method currently returns the object of loaded packages as-is, which made it difficult to add new features to formatters for backward compatibility reasons. The new `eslint.loadFormatter()` method returns an adapter object that wraps the object of loaded packages, to ease the process of adding new features. Additionally, the adapter object has access to the `ESLint` instance to calculate default data (using loaded plugin rules to make `rulesMeta`, for example). As a result, the `ESLint` class only implements an instance version of the `loadFormatter()` method. * ※2 Since ESLint 6, ESLint uses different logic from the `resolveFileGlobPatterns()` method to iterate files, making this method obsolete. **Related issue(s):** [RFC40](https://github.com/eslint/rfcs/blob/master/designs/2019-move-to-async-api/README.md), [#12939](https://github.com/eslint/eslint/pull/12939)
programming_docs
eslint Migrating to v6.0.0 Migrating to v6.0.0 =================== ESLint v6.0.0 is a major release of ESLint. We have made a few breaking changes in this release. This guide is intended to walk you through the breaking changes. The lists below are ordered roughly by the number of users each change is expected to affect, where the first items are expected to affect the most users. Breaking changes for users -------------------------- 1. [Node.js 6 is no longer supported](#drop-node-6) 2. [`eslint:recommended` has been updated](#eslint-recommended-changes) 3. [Plugins and shareable configs are no longer affected by ESLint’s location](#package-loading-simplification) 4. [The default parser now validates options more strictly](#espree-validation) 5. [Rule configuration are validated more strictly](#rule-config-validating) 6. [The `no-redeclare` rule is now more strict by default](#no-redeclare-updates) 7. [The `comma-dangle` rule is now more strict by default](#comma-dangle-updates) 8. [The `no-confusing-arrow` rule is now more lenient by default](#no-confusing-arrow-updates) 9. [Overrides in a config file can now match dotfiles](#overrides-dotfiles) 10. [Overrides in an extended config file can now be overridden by a parent config file](#overrides-precedence) 11. [Configuration values for globals are now validated](#globals-validation) 12. [The deprecated `experimentalObjectRestSpread` option has been removed](#experimental-object-rest-spread) 13. [User-provided regular expressions in rule options are parsed with the unicode flag](#unicode-regexes) Breaking changes for plugin/custom rule developers -------------------------------------------------- 1. [Plugin authors may need to update installation instructions](#plugin-documentation) 2. [`RuleTester` now validates against invalid `default` keywords in rule schemas](#rule-tester-defaults) 3. [`RuleTester` now requires an absolute path on `parser` option](#rule-tester-parser) 4. [The `eslintExplicitGlobalComment` scope analysis property has been removed](#eslintExplicitGlobalComment) Breaking changes for integration developers ------------------------------------------- 1. [Plugins and shareable configs are no longer affected by ESLint’s location](#package-loading-simplification) 2. [`Linter` no longer tries to load missing parsers from the filesystem](#linter-parsers) Node.js 6 is no longer supported ---------------------------------- As of April 2019, Node.js 6 will be at EOL and will no longer be receiving security updates. As a result, we have decided to drop support for it in ESLint v6. We now support the following versions of Node.js: * Node.js 8 (8.10.0 and above) * Node.js 10 (10.13.0 and above) * Anything above Node.js 11.10.1 **To address:** Make sure you upgrade to at least Node.js 8 when using ESLint v6. If you are unable to upgrade, we recommend continuing to use ESLint v5.x until you are able to upgrade Node.js. **Related issue(s):** [eslint/eslint#11546](https://github.com/eslint/eslint/issues/11456) `eslint:recommended` has been updated -------------------------------------- The following rules have been added to the [`eslint:recommended`](migrating-to-6.0.0../user-guide/configuring#using-eslintrecommended) config: * [`no-async-promise-executor`](migrating-to-6.0.0../rules/no-async-promise-executor) disallows using an `async` function as the argument to the `Promise` constructor, which is usually a bug. * [`no-misleading-character-class`](migrating-to-6.0.0../rules/no-misleading-character-class) reports character classes in regular expressions that might not behave as expected. * [`no-prototype-builtins`](migrating-to-6.0.0../rules/no-prototype-builtins) reports method calls like `foo.hasOwnProperty("bar")` (which are a frequent source of bugs), and suggests that they be replaced with `Object.prototype.hasOwnProperty.call(foo, "bar")` instead. * [`no-shadow-restricted-names`](migrating-to-6.0.0../rules/no-shadow-restricted-names) disallows shadowing variables like `undefined` (e.g. with code like `let undefined = 5;`), since is likely to confuse readers. * [`no-useless-catch`](migrating-to-6.0.0../rules/no-useless-catch) reports `catch` clauses that are redundant and can be removed from the code without changing its behavior. * [`no-with`](migrating-to-6.0.0../rules/no-with) disallows use of the [`with` statement](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/with), which can make code difficult to understand and cause compatibility problems. * [`require-atomic-updates`](migrating-to-6.0.0../rules/require-atomic-updates) reports race condition bugs that can occur when reassigning variables in async functions. Additionally, the following rule has been *removed* from `eslint:recommended`: * [`no-console`](migrating-to-6.0.0../rules/no-console) disallows calling functions like `console.log`. While this rule is useful in many cases (e.g. to avoid inadvertently leaving debugging statements in production code), it is not as broadly applicable as the other rules in `eslint:recommended`, and it was a source of false positives in cases where `console.log` is acceptable (e.g. in CLI applications). Finally, in ESLint v5 `eslint:recommended` would explicitly disable all core rules that were not considered “recommended”. This could cause confusing behavior if `eslint:recommended` was loaded after another config, since `eslint:recommended` would have the effect of turning off some rules. In ESLint v6, `eslint:recommended` has no effect on non-recommended rules. **To address:** To mimic the `eslint:recommended` behavior from 5.x, you can explicitly disable/enable rules in a config file as follows: ``` { "extends": "eslint:recommended", "rules": { "no-async-promise-executor": "off", "no-misleading-character-class": "off", "no-prototype-builtins": "off", "no-shadow-restricted-names": "off", "no-useless-catch": "off", "no-with": "off", "require-atomic-updates": "off", "no-console": "error" } } ``` In rare cases (if you were relying on the previous behavior where `eslint:recommended` disables core rules), you might need to disable additional rules to restore the previous behavior. **Related issue(s):** [eslint/eslint#10768](https://github.com/eslint/eslint/issues/10768), [eslint/eslint#10873](https://github.com/eslint/eslint/issues/10873) Plugins and shareable configs are no longer affected by ESLint’s location --------------------------------------------------------------------------- Previously, ESLint loaded plugins relative to the location of the ESLint package itself. As a result, we suggested that users with global ESLint installations should also install plugins globally, and users with local ESLint installations should install plugins locally. However, due to a design bug, this strategy caused ESLint to randomly fail to load plugins and shareable configs under certain circumstances, particularly when using package management tools like [`lerna`](https://github.com/lerna/lerna) and [Yarn Plug n’ Play](https://yarnpkg.com/lang/en/docs/pnp/). As a rule of thumb: With ESLint v6, plugins should always be installed locally, even if ESLint was installed globally. More precisely, ESLint v6 resolves plugins relative to the end user’s project by default, and always resolves shareable configs and parsers relative to the location of the config file that imports them. **To address:** If you use a global installation of ESLint (e.g. installed with `npm install eslint --global`) along with plugins, you should install those plugins locally in the projects where you run ESLint. If your config file extends shareable configs and/or parsers, you should ensure that those packages are installed as dependencies of the project containing the config file. If you use a config file located outside of a local project (with the `--config` flag), consider installing the plugins as dependencies of that config file, and setting the [`--resolve-plugins-relative-to`](migrating-to-6.0.0./command-line-interface#--resolve-plugins-relative-to) flag to the location of the config file. **Related issue(s):** [eslint/eslint#10125](https://github.com/eslint/eslint/issues/10125), [eslint/rfcs#7](https://github.com/eslint/rfcs/pull/7) The default parser now validates options more strictly -------------------------------------------------------- `espree`, the default parser used by ESLint, will now raise an error in the following cases: * The `ecmaVersion` parser option is set to something other than a number, such as the string `"2015"`. (Previously, a non-number option would simply be ignored.) * The `sourceType: "module"` parser option is set while `ecmaVersion` is set to `5` or left unspecified. (Previously, setting `sourceType: "module"` would implicitly cause `ecmaVersion` to be set to a minimum of 2015, which could be surprising.) * The `sourceType` is set to anything other than `"script"` or `"module"`. **To address:** If your config sets `ecmaVersion` to something other than a number, you can restore the previous behavior by removing `ecmaVersion`. (However, you may want to double-check that your config is actually working as expected.) If your config sets `parserOptions: { sourceType: "module" }` without also setting `parserOptions.ecmaVersion`, you should add `parserOptions: { ecmaVersion: 2015 }` to restore the previous behavior. **Related issue(s):** [eslint/eslint#9687](https://github.com/eslint/eslint/issues/9687), [eslint/espree#384](https://github.com/eslint/espree/issues/384) Rule configuration are validated more strictly ------------------------------------------------ To catch config errors earlier, ESLint v6 will report a linting error if you are trying to configure a non-existent rule. | config | ESLint v5 | ESLint v6 | | --- | --- | --- | | `/*eslint-enable foo*/` | no error | linting error | | `/*eslint-disable(-line) foo*/` | no error | linting error | | `/*eslint foo: 0*/` | no error | linting error | | `{rules: {foo: 0}}` | no error | no error | | `{rules: {foo: 1}` | linting warning | linting error | **To address:** You can remove the non-existent rule in your (inline) config. **Related issue(s):** [eslint/eslint#9505](https://github.com/eslint/eslint/issues/9505) The `no-redeclare` rule is now more strict by default ------------------------------------------------------- The default options for the [`no-redeclare`](migrating-to-6.0.0../rules/no-redeclare) rule have changed from `{ builtinGlobals: false }` to `{ builtinGlobals: true }`. Additionally, the `no-redeclare` rule will now report an error for globals enabled by comments like `/* global foo */` if those globals were already enabled through configuration anyway. **To address:** To restore the previous options for the rule, you can configure it as follows: ``` { "rules": { "no-redeclare": ["error", { "builtinGlobals": false }] } } ``` Additionally, if you see new errors for `global` comments in your code, you should remove those comments. **Related issue(s):** [eslint/eslint#11370](https://github.com/eslint/eslint/issues/11370), [eslint/eslint#11405](https://github.com/eslint/eslint/issues/11405) The `comma-dangle` rule is now more strict by default ------------------------------------------------------- Previously, the [`comma-dangle`](migrating-to-6.0.0../rules/comma-dangle) rule would ignore trailing function arguments and parameters, unless explicitly configured to check for function commas. In ESLint v6, function commas are treated the same way as other types of trailing commas. **To address:** You can restore the previous default behavior of the rule with: ``` { "rules": { "comma-dangle": ["error", { "arrays": "never", "objects": "never", "imports": "never", "exports": "never", "functions": "ignore" }] } } ``` To restore the previous behavior of a string option like `"always-multiline"`, replace `"never"` with `"always-multiline"` in the example above. **Related issue(s):** [eslint/eslint#11502](https://github.com/eslint/eslint/issues/11502) The `no-confusing-arrow` rule is now more lenient by default -------------------------------------------------------------- The default options for the [`no-confusing-arrow`](migrating-to-6.0.0../rules/no-confusing-arrow) rule have changed from `{ allowParens: false }` to `{ allowParens: true }`. **To address:** You can restore the previous default behavior of the rule with: ``` { "rules": { "no-confusing-arrow": ["error", { "allowParens": false }] } } ``` **Related issue(s):** [eslint/eslint#11503](https://github.com/eslint/eslint/issues/11503) Overrides in a config file can now match dotfiles --------------------------------------------------- Due to a bug, the glob patterns in a `files` list in an `overrides` section of a config file would never match dotfiles, making it impossible to have overrides apply to files starting with a dot. This bug has been fixed in ESLint v6. **To address:** If you don’t want dotfiles to be matched by an override, consider adding something like `excludedFiles: [".*"]` to that `overrides` section. See the [documentation](migrating-to-6.0.0../user-guide/configuring#configuration-based-on-glob-patterns) for more details. **Related issue(s):** [eslint/eslint#11201](https://github.com/eslint/eslint/issues/11201) Overrides in an extended config file can now be overridden by a parent config file ------------------------------------------------------------------------------------ Due to a bug, it was previously the case that an `overrides` block in a shareable config had precedence over the top level of a parent config. For example, with the following config setup, the `semi` rule would end up enabled even though it was explicitly disabled in the end user’s config: ``` // .eslintrc.js module.exports = { extends: ["foo"], rules: { semi: "off" } }; ``` ``` // eslint-config-foo/index.js module.exports = { overrides: { files: ["\*.js"], rules: { semi: "error" } } }; ``` In ESLint v6.0.0, a parent config always has precedence over extended configs, even with `overrides` blocks. **To address:** We expect the impact of this issue to be very low because most shareable configs don’t use `overrides` blocks. However, if you use a shareable config with `overrides` blocks, you might encounter a change in behavior due to something that is explicitly specified in your config but was inactive until now. If you would rather inherit the behavior from the shareable config, simply remove the corresponding entry from your own config. (In the example above, the previous behavior could be restored by removing `semi: "off"` from `.eslintrc.js`.) **Related issue(s):** [eslint/eslint#11510](https://github.com/eslint/eslint/issues/11510) Configuration values for globals are now validated ---------------------------------------------------- Previously, when configuring a set of global variables with an object, it was possible to use anything as the values of the object. An unknown value would be treated the same as `"writable"`. ``` // .eslintrc.js module.exports = { globals: { foo: "readonly", bar: "writable", baz: "hello!" // ??? } }; ``` With this change, any unknown values in a `globals` object result in a config validation error. **To address:** If you see config validation errors related to globals after updating, ensure that all values configured for globals are either `readonly`, `writable`, or `off`. (ESLint also accepts some alternate spellings and variants for compatibility.) The deprecated `experimentalObjectRestSpread` option has been removed ----------------------------------------------------------------------- Previously, when using the default parser, a config could use the `experimentalObjectRestSpread` option to enable parsing support for object rest/spread properties: ``` { "parserOptions": { "ecmaFeatures": { "experimentalObjectRestSpread": true } } } ``` Since ESLint v5, `ecmaFeatures: { experimentalObjectRestSpread: true }` has been equivalent to `ecmaVersion: 2018`, and has also emitted a deprecation warning. In ESLint v6, the `experimentalObjectRestSpread` feature has been removed entirely and has no effect. If your config was relying on `experimentalObjectRestSpread` to enable ES2018 parsing, you might start seeing parsing errors for recent syntax. **To address:** If you use the `experimentalObjectRestSpread` option, you should change your config to contain this instead: ``` { "parserOptions": { "ecmaVersion": 2018 } } ``` If you’re not sure which config file needs to be updated, it may be useful to run ESLint v5 and look at what config file is mentioned in the deprecation warning. **Related issue(s):** [eslint/eslint#9990](https://github.com/eslint/eslint/issues/9990) User-provided regular expressions in rule options are parsed with the unicode flag ------------------------------------------------------------------------------------ Rules like [`max-len`](migrating-to-6.0.0../rules/max-len) accept a string option which is interpreted as a regular expression. In ESLint v6.0.0, these regular expressions are interpreted with the [unicode flag](https://mathiasbynens.be/notes/es6-unicode-regex), which should exhibit more reasonable behavior when matching characters like astral symbols. Unicode regexes also validate escape sequences more strictly than non-unicode regexes. **To address:** If you get rule option validation errors after upgrading, ensure that any regular expressions in your rule options have no invalid escape sequences. **Related issue(s):** [eslint/eslint#11423](https://github.com/eslint/eslint/issues/11423) Plugin authors may need to update installation instructions ------------------------------------------------------------- If you maintain a plugin and provide installation instructions, you should ensure that the installation instructions are up to date with the [user-facing changes to how plugins are loaded](#package-loading-simplification). In particular, if your plugin was generated with the [`generator-eslint`](https://github.com/eslint/generator-eslint) package, it likely contains outdated instructions for how to use the plugin with global ESLint installations. **Related issue(s):** [eslint/rfcs#7](https://github.com/eslint/rfcs/pull/7) `RuleTester` now validates against invalid `default` keywords in rule schemas ------------------------------------------------------------------------------ In some cases, rule schemas can use the `default` keyword to automatically specify default values for rule options. However, the `default` keyword is only effective in certain schema locations, and is ignored elsewhere, which creates a risk of bugs if a rule incorrectly expects a default value to be provided as a rule option. In ESLint v6.0.0, `RuleTester` will raise an error if a rule has an invalid `default` keyword in its schema. **To address:** If `RuleTester` starts reporting an error about an invalid default, you can remove the `default` property at the indicated location in your rule schema, and the rule will behave the same way. (If this happens, you might also want to verify that the rule behaves correctly when no option value is provided in that location.) **Related issue(s):** [eslint/eslint#11473](https://github.com/eslint/eslint/issues/11473) `RuleTester` now requires an absolute path on `parser` option -------------------------------------------------------------- To use custom parsers in tests, we could use `parser` property with a package name or file path. However, if a package name was given, it’s unclear where the tester should load the parser package from because the tester doesn’t know which files are running the tester. In ESLint v6.0.0, `RuleTester` disallows `parser` property with a package name. **To address:** If you use `parser` property with package names in test cases, update it with `require.resolve()` function to resolve the package name to the absolute path to the package. **Related issue(s):** [eslint/eslint#11728](https://github.com/eslint/eslint/issues/11728), [eslint/eslint#10125](https://github.com/eslint/eslint/issues/10125), [eslint/rfcs#7](https://github.com/eslint/rfcs/pull/7) The `eslintExplicitGlobalComment` scope analysis property has been removed ---------------------------------------------------------------------------- Previously, ESLint would add an `eslintExplicitGlobalComment` property to `Variable` objects in scope analysis to indicate that a variable was introduced as a result of a `/* global */` comment. This property was undocumented, and the ESLint team was unable to find any usage of the property outside of ESLint core. The property has been removed in ESLint v6, and replaced with the `eslintExplicitGlobalComments` property, which can contain a list of all `/* global */` comments if a variable was declared with more than one of them. **To address:** If you maintain a rule that uses the `eslintExplicitGlobalComment` property, update it to use the `eslintExplicitGlobalComments` property as a list instead. **Related issue(s):** [eslint/rfcs#17](https://github.com/eslint/rfcs/pull/17) `Linter` no longer tries to load missing parsers from the filesystem --------------------------------------------------------------------- Previously, when linting code with a parser that had not been previously defined, the `Linter` API would attempt to load the parser from the filesystem. However, this behavior was confusing because `Linter` never access the filesystem in any other cases, and it was difficult to ensure that the correct parser would be found when loading the parser from the filesystem. In ESLint v6, `Linter` will no longer perform any filesystem operations, including loading parsers. **To address:** If you’re using `Linter` with a custom parser, use [`Linter#defineParser`](migrating-to-6.0.0../developer-guide/nodejs-api#linterdefineparser) to explicitly define the parser before linting any code. **Related issue(s):** [eslint/rfcs#7](https://github.com/eslint/rfcs/pull/7)
programming_docs
eslint Integrations Integrations ============ This page contains community projects that have integrated ESLint. The projects on this page are not maintained by the ESLint team. If you would like to recommend an integration to be added to this page, [submit a pull request](integrations../developer-guide/contributing/pull-requests). Editors ------- * Sublime Text 3: + [SublimeLinter-eslint](https://github.com/roadhump/SublimeLinter-eslint) + [Build Next](https://github.com/albertosantini/sublimetext-buildnext) * Vim: + [ALE](https://github.com/w0rp/ale) + [Syntastic](https://github.com/vim-syntastic/syntastic/tree/master/syntax_checkers/javascript) * Emacs: [Flycheck](http://www.flycheck.org/) supports ESLint with the [javascript-eslint](http://www.flycheck.org/en/latest/languages.html#javascript) checker. * Eclipse Orion: ESLint is the [default linter](https://dev.eclipse.org/mhonarc/lists/orion-dev/msg02718.html) * Eclipse IDE: [Tern ESLint linter](https://github.com/angelozerr/tern.java/wiki/Tern-Linter-ESLint) * TextMate 2: + [eslint.tmbundle](https://github.com/ryanfitzer/eslint.tmbundle) + [javascript-eslint.tmbundle](https://github.com/natesilva/javascript-eslint.tmbundle) * Atom: + [linter-eslint](https://atom.io/packages/linter-eslint) + [fast-eslint-8](https://atom.io/packages/fast-eslint-8) * IntelliJ IDEA, WebStorm, PhpStorm, PyCharm, RubyMine, and other JetBrains IDEs: [How to use ESLint](https://www.jetbrains.com/help/webstorm/eslint.html) * Visual Studio: [Linting JavaScript in VS](https://learn.microsoft.com/en-us/visualstudio/javascript/linting-javascript?view=vs-2022) * Visual Studio Code: [ESLint Extension](https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint) * Brackets: Included and [Brackets ESLint](https://github.com/brackets-userland/brackets-eslint) Build tools ----------- * Grunt: [grunt-eslint](https://www.npmjs.com/package/grunt-eslint) * Gulp: [gulp-eslint](https://www.npmjs.com/package/gulp-eslint) * Mimosa: [mimosa-eslint](https://www.npmjs.com/package/mimosa-eslint) * Broccoli: [broccoli-eslint](https://www.npmjs.com/package/broccoli-eslint) * Browserify: [eslintify](https://www.npmjs.com/package/eslintify) * Webpack: [eslint-webpack-plugin](https://www.npmjs.com/package/eslint-webpack-plugin) * Rollup: [@rollup/plugin-eslint](https://www.npmjs.com/package/@rollup/plugin-eslint) * Ember-cli: [ember-cli-eslint](https://www.npmjs.com/package/ember-cli-eslint) * Sails.js: [sails-hook-lint](https://www.npmjs.com/package/sails-hook-lint), [sails-eslint](https://www.npmjs.com/package/sails-eslint) * Start: [@start/plugin-lib-eslint](https://www.npmjs.com/package/@start/plugin-lib-eslint) * Brunch: [eslint-brunch](https://www.npmjs.com/package/eslint-brunch) Command Line Tools ------------------ * [ESLint Watch](https://www.npmjs.com/package/eslint-watch) * [Code Climate CLI](https://github.com/codeclimate/codeclimate) * [ESLint Nibble](https://github.com/IanVS/eslint-nibble) Source Control -------------- * [Git Precommit Hook](https://coderwall.com/p/zq8jlq/eslint-pre-commit-hook) * [Git pre-commit hook that only lints staged changes](https://gist.github.com/dahjelle/8ddedf0aebd488208a9a7c829f19b9e8) * [overcommit Git hook manager](https://github.com/brigade/overcommit) * [Mega-Linter](https://nvuillam.github.io/mega-linter): Linters aggregator for CI, [embedding eslint](https://nvuillam.github.io/mega-linter/descriptors/javascript_eslint/) Testing ------- * Mocha.js: [mocha-eslint](https://www.npmjs.com/package/mocha-eslint) Other Integration Lists ----------------------- You can find a curated list of other popular integrations for ESLint in the [awesome-eslint](https://github.com/dustinspecker/awesome-eslint) GitHub repository. eslint Migrating to v3.0.0 Migrating to v3.0.0 =================== ESLint v3.0.0 is the third major version release. We have made several breaking changes in this release, however, we believe the changes to be small enough that they should not require significant changes for ESLint users. This guide is intended to walk you through the changes. Dropping Support for Node.js < 4 -------------------------------- With ESLint v3.0.0, we are dropping support for Node.js versions prior to 4. Node.js 0.10 and 0.12 are in [maintenance mode](https://github.com/nodejs/Release) and Node.js 4 is the current LTS version. If you are using an older version of Node.js, we recommend upgrading to at least Node.js 4 as soon as possible. If you are unable to upgrade to Node.js 4 or higher, then we recommend continuing to use ESLint v2.x until you are ready to upgrade Node.js. **Important:** We will not be updating the ESLint v2.x versions going forward. All bug fixes and enhancements will land in ESLint v3.x. Requiring Configuration to Run ------------------------------ ESLint v3.0.0 now requires that you use a configuration to run. A configuration can be any of the following: 1. A `.eslintrc.js`, `.eslintrc.json`, `.eslintrc.yml`, `.eslintrc.yaml`, or `.eslintrc` file either in your project or home directory. 2. Configuration options passed on the command line using `--rule` (or to CLIEngine using `rules`). 3. A configuration file passed on the command line using `-c` (or to CLIEngine using `configFile`). 4. A base configuration is provided to CLIEngine using the `baseConfig` option. If ESLint can’t find a configuration, then it will throw an error and ask you to provide one. This change was made to help new ESLint users who are frequently confused that ESLint does nothing by default besides reporting parser errors. We anticipate this change will have minimal impact on most established users because you’re more likely to have configuration files already. **To Address:** You should be sure to use a configuration whenever you run ESLint. However, you can still run ESLint without a configuration by passing the `--no-eslintrc` option on the command line or setting the `useEslintrc` option to `false` for `CLIEngine`. To create a new configuration, use `eslint --init`. Changes to `"eslint:recommended"` --------------------------------- ``` { "extends": "eslint:recommended" } ``` In 3.0.0, the following rules were added to `"eslint:recommended"`: * [`no-unsafe-finally`](migrating-to-3.0.0../rules/no-unsafe-finally) helps catch `finally` clauses that may not behave as you think. * [`no-native-reassign`](migrating-to-3.0.0../rules/no-native-reassign) was previously part of `no-undef`, but was split out because it didn’t make sense as part of another rule. The `no-native-reassign` rule warns whenever you try to overwrite a read-only global variable. * [`require-yield`](migrating-to-3.0.0../rules/require-yield) helps to identify generator functions that do not have the `yield` keyword. The following rules were removed from `"eslint:recommended"`: * [`comma-dangle`](migrating-to-3.0.0../rules/comma-dangle) used to be recommended because Internet Explorer 8 and earlier threw a syntax error when it found a dangling comma on object literal properties. However, [Internet Explorer 8 was end-of-lifed](https://www.microsoft.com/en-us/WindowsForBusiness/End-of-IE-support) in January 2016 and all other active browsers allow dangling commas. As such, we consider dangling commas to now be a stylistic issue instead of a possible error. The following rules were modified: * [`complexity`](migrating-to-3.0.0../rules/complexity) used to have a hardcoded default of 11 in `eslint:recommended` that would be used if you turned the rule on without specifying a maximum. The default is now 20. The rule actually always had a default of 20, but `eslint:recommended` was overriding it by mistake. **To address:** If you want to mimic how `eslint:recommended` worked in v2.x, you can use the following: ``` { "extends": "eslint:recommended", "rules": { "no-unsafe-finally": "off", "no-native-reassign": "off", "complexity": ["off", 11], "comma-dangle": "error", "require-yield": "error" } } ``` Changes to `CLIEngine#executeOnText()` -------------------------------------- The `CLIEngine#executeOnText()` method has changed to work more like `CLIEngine#executeOnFiles()`. In v2.x, `CLIEngine#executeOnText()` warned about ignored files by default and didn’t have a way to opt-out of those warnings whereas `CLIEngine#executeOnFiles()` did not warn about ignored files by default and allowed you to opt-in to warning about them. The `CLIEngine#executeOnText()` method now also does not warn about ignored files by default and allows you to opt-in with a new, third argument (a boolean, `true` to warn about ignored files and `false` to not warn). **To address:** If you are currently using `CLIEngine#executeOnText()` in your project like this: ``` var result = engine.executeOnText(text, filename); ``` You can get the equivalent behavior using this: ``` var result = engine.executeOnText(text, filename, true); ``` If you do not want ignored file warnings output to the console, you can omit the third argument or pass `false`. eslint Migrating to v2.0.0 Migrating to v2.0.0 =================== ESLint v2.0.0 is the second major version release. As a result, there are some significant changes between how ESLint worked during its life in 0.x and 1.x and how it will work going forward. These changes are the direct result of feedback from the ESLint community of users and were not made without due consideration for the upgrade path. We believe that these changes make ESLint even better, and while some work is necessary to upgrade, we hope the pain of this upgrade is small enough that you will see the benefit of upgrading. **Important:** If you are upgrading from 0.x, please refer to [Migrating to 1.0.0](migrating-to-2.0.0./migrating-to-1.0.0) as your starting point. Rule Schema Changes ------------------- Due to a quirk in the way rule schemas worked, it was possible that you’d need to account for the rule severity (0, 1, or 2) in a rule schema if the options were sufficiently complex. That would result in a schema such as: ``` module.exports = { "type": "array", "items": [ { "enum": [0, 1, 2] }, { "enum": ["always", "never"] } ], "minItems": 1, "maxItems": 2 }; ``` This was confusing to rule developers as it seemed that rules shouldn’t be in charge of validating their own severity. In 2.0.0, rules no longer need to check their own severity. **To address:** If you are exporting a rule schema that checks severity, you need to make several changes: 1. Remove the severity from the schema 2. Adjust `minItems` from 1 to 0 3. Adjust `maxItems` by subtracting 1 Here’s what the schema from above looks like when properly converted: ``` module.exports = { "type": "array", "items": [ { "enum": ["always", "never"] } ], "minItems": 0, "maxItems": 1 }; ``` Removed Rules ------------- The following rules have been deprecated with new rules created to take their place. The following is a list of the removed rules and their replacements: * [no-arrow-condition](migrating-to-2.0.0../rules/no-arrow-condition) is replaced by a combination of [no-confusing-arrow](migrating-to-2.0.0../rules/no-confusing-arrow) and [no-constant-condition](migrating-to-2.0.0../rules/no-constant-condition). Turn on both of these rules to get the same functionality as `no-arrow-condition`. * [no-empty-label](migrating-to-2.0.0../rules/no-empty-label) is replaced by [no-labels](migrating-to-2.0.0../rules/no-labels) with `{"allowLoop": true, "allowSwitch": true}` option. * [space-after-keywords](migrating-to-2.0.0../rules/space-after-keywords) is replaced by [keyword-spacing](migrating-to-2.0.0../rules/keyword-spacing). * [space-before-keywords](migrating-to-2.0.0../rules/space-before-keywords) is replaced by [keyword-spacing](migrating-to-2.0.0../rules/keyword-spacing). * [space-return-throw-case](migrating-to-2.0.0../rules/space-return-throw-case) is replaced by [keyword-spacing](migrating-to-2.0.0../rules/keyword-spacing). **To address:** You’ll need to update your rule configurations to use the new rules. ESLint v2.0.0 will also warn you when you’re using a rule that has been removed and will suggest the replacement rules. Hopefully, this will result in few surprises during the upgrade process. Configuration Cascading Changes ------------------------------- Prior to 2.0.0, if a directory contained both an `.eslintrc` file and a `package.json` file with ESLint configuration information, the settings from the two files would be merged together. In 2.0.0, only the settings from the `.eslintrc.*` file are used and the ones in `package.json` are ignored when both are present. Otherwise, `package.json` can still be used with ESLint configuration, but only if no other `.eslintrc.*` files are present. **To address:** If you have both an `.eslintrc.*` and `package.json` with ESLint configuration information in the same directory, combine your configurations into just one of those files. Built-In Global Variables ------------------------- Prior to 2.0.0, new global variables that were standardized as part of ES6 such as `Promise`, `Map`, `Set`, and `Symbol` were included in the built-in global environment. This could lead to potential issues when, for example, `no-undef` permitted use of the `Promise` constructor even in ES5 code where promises are unavailable. In 2.0.0, the built-in environment only includes the standard ES5 global variables, and the new ES6 global variables have been moved to the `es6` environment. **To address:** If you are writing ES6 code, enable the `es6` environment if you have not already done so: ``` // In your .eslintrc { env: { es6: true } } // Or in a configuration comment /\*eslint-env es6\*/ ``` Language Options ---------------- Prior to 2.0.0, the way to enable language options was by using `ecmaFeatures` in your configuration. In 2.0.0: * The `ecmaFeatures` property is now under a top-level `parserOptions` property. * All ECMAScript 6 `ecmaFeatures` flags have been removed in favor of a `ecmaVersion` property under `parserOptions` that can be set to 3, 5 (default), or 6. * The `ecmaFeatures.modules` flag has been replaced by a `sourceType` property under `parserOptions` which can be set to `"script"` (default) or `"module"` for ES6 modules. **To address:** If you are using any ECMAScript 6 feature flags in `ecmaFeatures`, you’ll need to use `ecmaVersion: 6` instead. The ECMAScript 6 feature flags are: * `arrowFunctions` - enable [arrow functions](https://leanpub.com/understandinges6/read#leanpub-auto-arrow-functions) * `binaryLiterals` - enable [binary literals](https://leanpub.com/understandinges6/read#leanpub-auto-octal-and-binary-literals) * `blockBindings` - enable `let` and `const` (aka [block bindings](https://leanpub.com/understandinges6/read#leanpub-auto-block-bindings)) * `classes` - enable classes * `defaultParams` - enable [default function parameters](https://leanpub.com/understandinges6/read/#leanpub-auto-default-parameters) * `destructuring` - enable [destructuring](https://leanpub.com/understandinges6/read#leanpub-auto-destructuring-assignment) * `forOf` - enable [`for-of` loops](https://leanpub.com/understandinges6/read#leanpub-auto-iterables-and-for-of) * `generators` - enable [generators](https://leanpub.com/understandinges6/read#leanpub-auto-generators) * `modules` - enable modules and global strict mode * `objectLiteralComputedProperties` - enable [computed object literal property names](https://leanpub.com/understandinges6/read#leanpub-auto-computed-property-names) * `objectLiteralDuplicateProperties` - enable [duplicate object literal properties](https://leanpub.com/understandinges6/read#leanpub-auto-duplicate-object-literal-properties) in strict mode * `objectLiteralShorthandMethods` - enable [object literal shorthand methods](https://leanpub.com/understandinges6/read#leanpub-auto-method-initializer-shorthand) * `objectLiteralShorthandProperties` - enable [object literal shorthand properties](https://leanpub.com/understandinges6/read#leanpub-auto-property-initializer-shorthand) * `octalLiterals` - enable [octal literals](https://leanpub.com/understandinges6/read#leanpub-auto-octal-and-binary-literals) * `regexUFlag` - enable the [regular expression `u` flag](https://leanpub.com/understandinges6/read#leanpub-auto-the-regular-expression-u-flag) * `regexYFlag` - enable the [regular expression `y` flag](https://leanpub.com/understandinges6/read#leanpub-auto-the-regular-expression-y-flag) * `restParams` - enable the [rest parameters](https://leanpub.com/understandinges6/read#leanpub-auto-rest-parameters) * `spread` - enable the [spread operator](https://leanpub.com/understandinges6/read#leanpub-auto-the-spread-operator) for arrays * `superInFunctions` - enable `super` references inside of functions * `templateStrings` - enable [template strings](https://leanpub.com/understandinges6/read/#leanpub-auto-template-strings) * `unicodeCodePointEscapes` - enable [code point escapes](https://leanpub.com/understandinges6/read/#leanpub-auto-escaping-non-bmp-characters) If you’re using any of these flags, such as: ``` { ecmaFeatures: { arrowFunctions: true } } ``` Then you should enable ES6 using `ecmaVersion`: ``` { parserOptions: { ecmaVersion: 6 } } ``` If you’re using any non-ES6 flags in `ecmaFeatures`, you need to move those inside of `parserOptions`. For instance: ``` { ecmaFeatures: { jsx: true } } ``` Then you should move `ecmaFeatures` under `parserOptions`: ``` { parserOptions: { ecmaFeatures: { jsx: true } } } ``` If you were using `ecmaFeatures.modules` to enable ES6 module support like this: ``` { ecmaFeatures: { modules: true } } ``` ``` { parserOptions: { sourceType: "module" } } ``` Additionally, if you are using `context.ecmaFeatures` inside of your rules, then you’ll need to update your code in the following ways: 1. If you’re using an ES6 feature flag such as `context.ecmaFeatures.blockBindings`, rewrite to check for `context.parserOptions.ecmaVersion > 5`. 2. If you’re using `context.ecmaFeatures.modules`, rewrite to check that the `sourceType` property of the Program node is `"module"`. 3. If you’re using a non-ES6 feature flag such as `context.ecmaFeatures.jsx`, rewrite to check for `context.parserOptions.ecmaFeatures.jsx`. If you have a plugin with rules and you are using RuleTester, then you also need to update the options you pass for rules that use `ecmaFeatures`. For example: ``` var ruleTester = new RuleTester(); ruleTester.run("no-var", rule, { valid: [ { code: "let x;", parserOptions: { ecmaVersion: 6 } } ] }); ``` If you’re not using `ecmaFeatures` in your configuration or your custom/plugin rules and tests, then no change is needed. New Rules in `"eslint:recommended"` ----------------------------------- ``` { "extends": "eslint:recommended" } ``` In 2.0.0, the following 11 rules were added to `"eslint:recommended"`. * [constructor-super](migrating-to-2.0.0../rules/constructor-super) * [no-case-declarations](migrating-to-2.0.0../rules/no-case-declarations) * [no-class-assign](migrating-to-2.0.0../rules/no-class-assign) * [no-const-assign](migrating-to-2.0.0../rules/no-const-assign) * [no-dupe-class-members](migrating-to-2.0.0../rules/no-dupe-class-members) * [no-empty-pattern](migrating-to-2.0.0../rules/no-empty-pattern) * [no-new-symbol](migrating-to-2.0.0../rules/no-new-symbol) * [no-self-assign](migrating-to-2.0.0../rules/no-self-assign) * [no-this-before-super](migrating-to-2.0.0../rules/no-this-before-super) * [no-unexpected-multiline](migrating-to-2.0.0../rules/no-unexpected-multiline) * [no-unused-labels](migrating-to-2.0.0../rules/no-unused-labels) **To address:** If you don’t want to be notified by those rules, you can simply disable those rules. ``` { "extends": "eslint:recommended", "rules": { "no-case-declarations": 0, "no-class-assign": 0, "no-const-assign": 0, "no-dupe-class-members": 0, "no-empty-pattern": 0, "no-new-symbol": 0, "no-self-assign": 0, "no-this-before-super": 0, "no-unexpected-multiline": 0, "no-unused-labels": 0, "constructor-super": 0 } } ``` Scope Analysis Changes ---------------------- We found some bugs in our scope analysis that needed to be addressed. Specifically, we were not properly accounting for global variables in all the ways they are defined. Originally, `Variable` objects and `Reference` objects refer each other: * `Variable#references` property is an array of `Reference` objects which are referencing the variable. * `Reference#resolved` property is a `Variable` object which are referenced. But until 1.x, the following variables and references had the wrong value (empty) in those properties: * `var` declarations in the global. * `function` declarations in the global. * Variables defined in config files. * Variables defined in `/* global */` comments. Now, those variables and references have correct values in these properties. `Scope#through` property has references where `Reference#resolved` is `null`. So as a result of this change, the value of `Scope#through` property was changed also. **To address:** If you are using `Scope#through` to find references of a built-in global variable, you need to make several changes. For example, this is how you might locate the `window` global variable in 1.x: ``` var globalScope = context.getScope(); globalScope.through.forEach(function(reference) { if (reference.identifier.name === "window") { checkForWindow(reference); } }); ``` This was a roundabout way to find the variable because it was added after the fact by ESLint. The `window` variable was in `Scope#through` because the definition couldn’t be found. In 2.0.0, `window` is no longer located in `Scope#through` because we have added back the correct declaration. That means you can reference the `window` object (or any other global object) directly. So the previous example would change to this: ``` var globalScope = context.getScope(); var variable = globalScope.set.get("window"); if (variable) { variable.references.forEach(checkForWindow); } ``` Further Reading: <https://estools.github.io/escope/> Default Changes When Using `eslint:recommended` ----------------------------------------------- This will affect you if you are extending from `eslint:recommended`, and are enabling [`no-multiple-empty-lines`](migrating-to-2.0.0../rules/no-multiple-empty-lines) or [`func-style`](migrating-to-2.0.0../rules/func-style) with only a severity, such as: ``` { "extends": "eslint:recommended", "rules": { "no-multiple-empty-lines": 2, "func-style": 2 } } ``` The rule `no-multiple-empty-lines` has no default exceptions, but in ESLint `1.x`, a default from `eslint:recommended` was applied such that a maximum of two empty lines would be permitted. The rule `func-style` has a default configuration of `"expression"`, but in ESLint `1.x`, `eslint:recommended` defaulted it to `"declaration"`. ESLint 2.0.0 removes these conflicting defaults, and so you may begin seeing linting errors related to these rules. **To address:** If you would like to maintain the previous behavior, update your configuration for `no-multiple-empty-lines` by adding `{"max": 2}`, and change `func-style` to `"declaration"`. For example: ``` { "extends": "eslint:recommended", "rules": { "no-multiple-empty-lines": [2, {"max": 2}], "func-style": [2, "declaration"] } } ``` SourceCode constructor (Node API) changes ----------------------------------------- `SourceCode` constructor got to handle Unicode BOM. If the first argument `text` has BOM, `SourceCode` constructor sets `true` to `this.hasBOM` and strips BOM from the text. ``` var SourceCode = require("eslint").SourceCode; var code = new SourceCode("\uFEFFvar foo = bar;", ast); assert(code.hasBOM === true); assert(code.text === "var foo = bar;"); ``` So the second argument `ast` also should be parsed from stripped text. **To address:** If you are using `SourceCode` constructor in your code, please parse the source code after it stripped BOM: ``` var ast = yourParser.parse(text.replace(/^\uFEFF/, ""), options); var sourceCode = new SourceCode(text, ast); ``` Rule Changes ------------ * [`strict`](migrating-to-2.0.0../rules/strict) - defaults to `"safe"` (previous default was `"function"`) Plugins No Longer Have Default Configurations --------------------------------------------- Prior to v2.0.0, plugins could specify a `rulesConfig` for the plugin. The `rulesConfig` would automatically be applied whenever someone uses the plugin, which is the opposite of what ESLint does in every other situation (where nothing is on by default). To bring plugins behavior in line, we have removed support for `rulesConfig` in plugins. **To address:** If you are using a plugin in your configuration file, you will need to manually enable the plugin rules in the configuration file.
programming_docs
eslint Migrating to v8.0.0 Migrating to v8.0.0 =================== ESLint v8.0.0 is a major release of ESLint. We have made a few breaking changes in this release. This guide is intended to walk you through the breaking changes. The lists below are ordered roughly by the number of users each change is expected to affect, where the first items are expected to affect the most users. Table of Contents ----------------- ### Breaking changes for users * [Node.js 10, 13, and 15 are no longer supported](#drop-old-node) * [Removed `codeframe` and `table` formatters](#removed-formatters) * [`comma-dangle` rule schema is stricter](#comma-dangle) * [Unused disable directives are now fixable](#directives) * [`eslint:recommended` has been updated](#eslint-recommended) ### Breaking changes for plugin developers * [Node.js 10, 13, and 15 are no longer supported](#drop-old-node) * [Rules require `meta.hasSuggestions` to provide suggestions](#suggestions) * [Rules require `meta.fixable` to provide fixes](#fixes) * [`SourceCode#getComments()` fails in `RuleTester`](#get-comments) * [Changes to shorthand property AST format](#ast-format) ### Breaking changes for integration developers * [Node.js 10, 13, and 15 are no longer supported](#drop-old-node) * [The `CLIEngine` class has been removed](#remove-cliengine) * [The `linter` object has been removed](#remove-linter) * [The `/lib` entrypoint has been removed](#remove-lib) Node.js 10, 13, and 15 are no longer supported ------------------------------------------------ Node.js 10, 13, 15 all reached end of life either in 2020 or early 2021. ESLint is officially dropping support for these versions of Node.js starting with ESLint v8.0.0. ESLint now supports the following versions of Node.js: * Node.js 12.22 and above * Node.js 14 and above * Node.js 16 and above **To address:** Make sure you upgrade to at least Node.js `12.22.0` when using ESLint v8.0.0. One important thing to double check is the Node.js version supported by your editor when using ESLint via editor integrations. If you are unable to upgrade, we recommend continuing to use ESLint 7 until you are able to upgrade Node.js. **Related issue(s):** [#14023](https://github.com/eslint/eslint/issues/14023) Removed `codeframe` and `table` formatters -------------------------------------------- ESLint v8.0.0 has removed the `codeframe` and `table` formatters from the core. These formatters required dependencies that weren’t used anywhere else in ESLint, and removing them allows us to reduce the size of ESLint, allowing for faster installation. **To address:** If you are using the `codeframe` or `table` formatters, you’ll need to install the standalone [`eslint-formatter-codeframe`](https://github.com/fregante/eslint-formatter-codeframe) or [`eslint-formatter-table`](https://github.com/fregante/eslint-formatter-table) packages, respectively, to be able to use them in ESLint v8.0.0. **Related issue(s):** [#14277](https://github.com/eslint/eslint/issues/14277), [#14316](https://github.com/eslint/eslint/pull/14316) `comma-dangle` rule schema is stricter --------------------------------------- In ESLint v7.0.0, the `comma-dangle` rule could be configured like this without error: ``` { "rules": { "comma-dangle": ["error", "never", { "arrays": "always" }] } } ``` With this configuration, the rule would ignore the third element in the array because only the second element is read. In ESLint v8.0.0, this configuration will cause ESLint to throw an error. **To address:** Change your rule configuration so that there are only two elements in the array, and the second element is either a string or an object, such as: ``` { "comma-dangle": ["error", "never"], } ``` or ``` { "comma-dangle": ["error", { "arrays": "never", "objects": "never", "imports": "never", "exports": "never", "functions": "never" }] } ``` **Related issue(s):** [#13739](https://github.com/eslint/eslint/issues/13739) Unused disable directives are now fixable ------------------------------------------- In ESLint v7.0.0, using both `--report-unused-disable-directives` and `--fix` on the command line would fix only rules but leave unused disable directives in place. In ESLint v8.0.0, this combination of command-line options will result in the unused disable directives being removed. **To address:** If you are using `--report-unused-disable-directives` and `--fix` together on the command line, and you don’t want unused disable directives to be removed, add `--fix-type problem,suggestion,layout` as a command line option. **Related issue(s):** [#11815](https://github.com/eslint/eslint/issues/11815) `eslint:recommended` has been updated -------------------------------------- Four new rules have been enabled in the `eslint:recommended` preset. * [`no-loss-of-precision`](migrating-to-8.0.0../rules/no-loss-of-precision) * [`no-nonoctal-decimal-escape`](migrating-to-8.0.0../rules/no-nonoctal-decimal-escape) * [`no-unsafe-optional-chaining`](migrating-to-8.0.0../rules/no-unsafe-optional-chaining) * [`no-useless-backreference`](migrating-to-8.0.0../rules/no-useless-backreference) **To address:** Fix errors or disable these rules. **Related issue(s):** [#14673](https://github.com/eslint/eslint/issues/14673) Rules require `meta.hasSuggestions` to provide suggestions ------------------------------------------------------------ In ESLint v7.0.0, rules that [provided suggestions](migrating-to-8.0.0../developer-guide/working-with-rules#providing-suggestions) did not need to let ESLint know. In v8.0.0, rules providing suggestions need to set their `meta.hasSuggestions` to `true`. This informs ESLint that the rule intends to provide suggestions. Without this property, any attempt to provide a suggestion will result in an error. **To address:** If your rule provides suggestions, add `meta.hasSuggestions` to the object, such as: ``` module.exports = { meta: { hasSuggestions: true }, create(context) { // your rule } }; ``` The [eslint-plugin/require-meta-has-suggestions](https://github.com/not-an-aardvark/eslint-plugin-eslint-plugin/blob/master/docs/rules/require-meta-has-suggestions.md) rule can automatically fix and enforce that your rules are properly specifying `meta.hasSuggestions`. **Related issue(s):** [#14312](https://github.com/eslint/eslint/issues/14312) Rules require `meta.fixable` to provide fixes ----------------------------------------------- In ESLint v7.0.0, rules that were written as a function (rather than object) were able to provide fixes. In ESLint v8.0.0, only rules written as an object are allowed to provide fixes and must have a `meta.fixable` property set to either `"code"` or `"whitespace"`. **To address:** If your rule makes fixes and is written as a function, such as: ``` module.exports = function(context) { // your rule }; ``` Then rewrite your rule in this format: ``` module.exports = { meta: { fixable: "code" // or "whitespace" }, create(context) { // your rule } }; ``` The [eslint-plugin/require-meta-fixable](https://github.com/not-an-aardvark/eslint-plugin-eslint-plugin/blob/master/docs/rules/require-meta-fixable.md) rule can automatically fix and enforce that your rules are properly specifying `meta.fixable`. The [eslint-plugin/prefer-object-rule](https://github.com/not-an-aardvark/eslint-plugin-eslint-plugin/blob/master/docs/rules/prefer-object-rule.md) rule can automatically fix and enforce that your rules are written with the object format instead of the deprecated function format. See the [rule documentation](migrating-to-8.0.0../developer-guide/working-with-rules) for more information on writing rules. **Related issue(s):** [#13349](https://github.com/eslint/eslint/issues/13349) `SourceCode#getComments()` fails in `RuleTester` ------------------------------------------------- Back in ESLint v4.0.0, we deprecated `SourceCode#getComments()`, but we neglected to remove it. Rather than removing it completely in v8.0.0, we are taking the intermediate step of updating `RuleTester` to fail when `SourceCode#getComments()` is used inside of a rule. As such, all existing rules will continue to work, but when the developer runs tests for the rule there will be a failure. The `SourceCode#getComments()` method will be removed in v9.0.0. **To address:** If your rule uses `SourceCode#getComments()`, please use [`SourceCode#getCommentsBefore()`, `SourceCode#getCommentsAfter()`, or `SourceCode#getCommentsInside()`](migrating-to-8.0.0../developer-guide/working-with-rules#sourcecodegetcommentsbefore-sourcecodegetcommentsafter-and-sourcecodegetcommentsinside). **Related issue(s):** [#14744](https://github.com/eslint/eslint/issues/14744) Changes to shorthand property AST format ------------------------------------------ ESLint v8.0.0 includes an upgrade to Espree v8.0.0 to support new syntax. This Espree upgrade, in turn, contains an upgrade to Acorn v8.0.0, which changed how shorthand properties were represented in the AST. Here’s an example: ``` const version = 8; const x = { version }; ``` This code creates a property node that looks like this: ``` { "type": "Property", "method": false, "shorthand": true, "computed": false, "key": { "type": "Identifier", "name": "version" }, "kind": "init", "value": { "type": "Identifier", "name": "version" } } ``` Note that both the `key` and the `value` properties contain the same information. Prior to Acorn v8.0.0 (and therefore prior to ESLint v8.0.0), these two nodes were represented by the same object, so you could use `===` to determine if they represented the same node, such as: ``` // true in ESLint v7.x, false in ESLint v8.0.0 if (propertyNode.key === propertyNode.value) { // do something } ``` In ESLint v8.0.0 (via Acorn v8.0.0), the key and value are now separate objects and therefore no longer equivalent. **To address:** If your rule makes a comparison between the key and value of a shorthand object literal property to determine if they are the same node, you’ll need to change your code in one of two ways: 1. Use `propertyNode.shorthand` to determine if the property is a shorthand property node. 2. Use the `range` property of each node to determine if the key and value occupy the same location. **Related issue(s):** [#14591](https://github.com/eslint/eslint/pull/14591#issuecomment-887733070) The `CLIEngine` class has been removed ---------------------------------------- The `CLIEngine` class has been removed and replaced by the [`ESLint` class](migrating-to-8.0.0../developer-guide/nodejs-api#eslint-class). **To address:** Update your code to use the new `ESLint` class if you are currently using `CLIEngine`. The following table maps the existing `CLIEngine` methods to their `ESLint` counterparts: | `CLIEngine` | `ESLint` | | --- | --- | | `executeOnFiles(patterns)` | `lintFiles(patterns)` | | `executeOnText(text, filePath, warnIgnored)` | `lintText(text, options)` | | `getFormatter(name)` | `loadFormatter(name)` | | `getConfigForFile(filePath)` | `calculateConfigForFile(filePath)` | | `isPathIgnored(filePath)` | `isPathIgnored(filePath)` | | `static outputFixes(results)` | `static outputFixes(results)` | | `static getErrorResults(results)` | `static getErrorResults(results)` | | `static getFormatter(name)` | (removed ※1) | | `addPlugin(pluginId, definition)` | the `plugins` constructor option | | `getRules()` | (removed ※2) | | `resolveFileGlobPatterns()` | (removed ※3) | * ※1 The `engine.getFormatter()` method currently returns the object of loaded packages as-is, which made it difficult to add new features to formatters for backward compatibility reasons. The new `eslint.loadFormatter()` method returns an adapter object that wraps the object of loaded packages, to ease the process of adding new features. Additionally, the adapter object has access to the `ESLint` instance to calculate default data (using loaded plugin rules to make `rulesMeta`, for example). As a result, the `ESLint` class only implements an instance version of the `loadFormatter()` method. * ※2 The `CLIEngine#getRules()` method had side effects and so was removed. If you were using `CLIEngine#getRules()` to retrieve meta information about rules based on linting results, use `ESLint#getRulesMetaForResults()` instead. If you were using `CLIEngine#getRules()` to retrieve all built-in rules, import `builtinRules` from `eslint/use-at-your-own-risk` for an unsupported API that allows access to internal rules. * ※3 Since ESLint v6.0.0, ESLint uses different logic from the `resolveFileGlobPatterns()` method to iterate files, making this method obsolete. **Related issue(s):** [RFC80](https://github.com/eslint/rfcs/tree/main/designs/2021-package-exports), [#14716](https://github.com/eslint/eslint/pull/14716), [#13654](https://github.com/eslint/eslint/issues/13654) The `linter` object has been removed -------------------------------------- The deprecated `linter` object has been removed from the ESLint package in v8.0.0. **To address:** If you are using the `linter` object, such as: ``` const { linter } = require("eslint"); ``` Change your code to this: ``` const { Linter } = require("eslint"); const linter = new Linter(); ``` **Related issue(s):** [RFC80](https://github.com/eslint/rfcs/tree/main/designs/2021-package-exports), [#14716](https://github.com/eslint/eslint/pull/14716), [#13654](https://github.com/eslint/eslint/issues/13654) The `/lib` entrypoint has been removed ---------------------------------------- Beginning in v8.0.0, ESLint is strictly defining its public API. Previously, you could reach into individual files such as `require("eslint/lib/rules/semi")` and this is no longer allowed. There are a limited number of existing APIs that are now available through the `/use-at-your-own-risk` entrypoint for backwards compatibility, but these APIs are not formally supported and may break or disappear at any point in time. **To address:** If you are accessing rules directly through the `/lib` entrypoint, such as: ``` const rule = require("eslint/lib/rules/semi"); ``` Change your code to this: ``` const { builtinRules } = require("eslint/use-at-your-own-risk"); const rule = builtinRules.get("semi"); ``` If you are accessing `FileEnumerator` directly through the `/lib` entrypoint, such as: ``` const { FileEnumerator } = require("eslint/lib/cli-engine/file-enumerator"); ``` Change your code to this: ``` const { FileEnumerator } = require("eslint/use-at-your-own-risk"); ``` **Related issue(s):** [RFC80](https://github.com/eslint/rfcs/tree/main/designs/2021-package-exports), [#14716](https://github.com/eslint/eslint/pull/14716), [#13654](https://github.com/eslint/eslint/issues/13654) eslint Migrating to v4.0.0 Migrating to v4.0.0 =================== ESLint v4.0.0 is the fourth major version release. We have made several breaking changes in this release; however, we expect that most of the changes will only affect a very small percentage of users. This guide is intended to walk you through the changes. The lists below are ordered roughly by the number of users each change is expected to affect, where the first items are expected to affect the most users. Breaking changes for users -------------------------- 1. [New rules have been added to `eslint:recommended`](#eslint-recommended-changes) 2. [The `indent` rule is more strict](#indent-rewrite) 3. [Unrecognized properties in config files now cause a fatal error](#config-validation) 4. [.eslintignore patterns are now resolved from the location of the file](#eslintignore-patterns) 5. [The `padded-blocks` rule is more strict by default](#padded-blocks-defaults) 6. [The `space-before-function-paren` rule is more strict by default](#space-before-function-paren-defaults) 7. [The `no-multi-spaces` rule is more strict by default](#no-multi-spaces-eol-comments) 8. [References to scoped plugins in config files are now required to include the scope](#scoped-plugin-resolution) Breaking changes for plugin/custom rule developers -------------------------------------------------- 1. [`RuleTester` now validates properties of test cases](#rule-tester-validation) 2. [AST nodes no longer have comment properties](#comment-attachment) 3. [`LineComment` and `BlockComment` events will no longer be emitted during AST traversal](#event-comments) 4. [Shebangs are now returned from comment APIs](#shebangs) Breaking changes for integration developers ------------------------------------------- 1. [The `global` property in the `linter.verify()` API is no longer supported](#global-property) 2. [More report messages now have full location ranges](#report-locations) 3. [Some exposed APIs are now ES2015 classes](#exposed-es2015-classes) `eslint:recommended` changes ----------------------------- Two new rules have been added to the [`eslint:recommended`](migrating-to-4.0.0configuring#using-eslintrecommended) config: * [`no-compare-neg-zero`](migrating-to-4.0.0../rules/no-compare-neg-zero) disallows comparisons to `-0` * [`no-useless-escape`](migrating-to-4.0.0../rules/no-useless-escape) disallows uselessly-escaped characters in strings and regular expressions **To address:** To mimic the `eslint:recommended` behavior from 3.x, you can disable these rules in a config file: ``` { "extends": "eslint:recommended", "rules": { "no-compare-neg-zero": "off", "no-useless-escape": "off" } } ``` The `indent` rule is more strict ---------------------------------- Previously, the [`indent`](migrating-to-4.0.0../rules/indent) rule was fairly lenient about checking indentation; there were many code patterns where indentation was not validated by the rule. This caused confusion for users, because they were accidentally writing code with incorrect indentation, and they expected ESLint to catch the issues. In 4.0.0, the `indent` rule has been rewritten. The new version of the rule will report some indentation errors that the old version of the rule did not catch. Additionally, the indentation of `MemberExpression` nodes, function parameters, and function arguments will now be checked by default (it was previously ignored by default for backwards compatibility). To make the upgrade process easier, we’ve introduced the [`indent-legacy`](migrating-to-4.0.0../rules/indent-legacy) rule as a snapshot of the `indent` rule from 3.x. If you run into issues from the `indent` rule when you upgrade, you should be able to use the `indent-legacy` rule to replicate the 3.x behavior. However, the `indent-legacy` rule is deprecated and will not receive bugfixes or improvements in the future, so you should eventually switch back to the `indent` rule. **To address:** We recommend upgrading without changing your `indent` configuration, and fixing any new indentation errors that appear in your codebase. However, if you want to mimic how the `indent` rule worked in 3.x, you can update your configuration: ``` { rules: { indent: "off", "indent-legacy": "error" // replace this with your previous `indent` configuration } } ``` Unrecognized properties in config files now cause a fatal error ----------------------------------------------------------------- When creating a config, users sometimes make typos or misunderstand how the config is supposed to be structured. Previously, ESLint did not validate the properties of a config file, so a typo in a config could be very tedious to debug. Starting in 4.0.0, ESLint will raise an error if a property in a config file is unrecognized or has the wrong type. **To address:** If you see a config validation error after upgrading, verify that your config doesn’t contain any typos. If you are using an unrecognized property, you should be able to remove it from your config to restore the previous behavior. .eslintignore patterns are now resolved from the location of the file ----------------------------------------------------------------------- Due to a bug, glob patterns in an `.eslintignore` file were previously resolved from the current working directory of the process, rather than the location of the `.eslintignore` file. Starting in 4.0, patterns in an `.eslintignore` file will be resolved from the `.eslintignore` file’s location. **To address:** If you use an `.eslintignore` file and you frequently run ESLint from somewhere other than the project root, it’s possible that the patterns will be matched differently. You should update the patterns in the `.eslintignore` file to ensure they are relative to the file, not to the working directory. The `padded-blocks` rule is more strict by default ---------------------------------------------------- By default, the [`padded-blocks`](migrating-to-4.0.0../rules/padded-blocks) rule will now enforce padding in class bodies and switch statements. Previously, the rule would ignore these cases unless the user opted into enforcing them. **To address:** If this change results in more linting errors in your codebase, you should fix them or reconfigure the rule. The `space-before-function-paren` rule is more strict by default ------------------------------------------------------------------ By default, the [`space-before-function-paren`](migrating-to-4.0.0../rules/space-before-function-paren) rule will now enforce spacing for async arrow functions. Previously, the rule would ignore these cases unless the user opted into enforcing them. **To address:** To mimic the default config from 3.x, you can use: ``` { "rules": { "space-before-function-paren": ["error", { "anonymous": "always", "named": "always", "asyncArrow": "ignore" }] } } ``` The `no-multi-spaces` rule is more strict by default ------------------------------------------------------ By default, the [`no-multi-spaces`](migrating-to-4.0.0../rules/no-multi-spaces) rule will now disallow multiple spaces before comments at the end of a line. Previously, the rule did not check this case. **To address:** To mimic the default config from 3.x, you can use: ``` { "rules": { "no-multi-spaces": ["error", {"ignoreEOLComments": true}] } } ``` References to scoped plugins in config files are now required to include the scope ------------------------------------------------------------------------------------ In 3.x, there was a bug where references to scoped NPM packages as plugins in config files could omit the scope. For example, in 3.x the following config was legal: ``` { "plugins": [ "@my-organization/foo" ], "rules": { "foo/some-rule": "error" } } ``` In other words, it was possible to reference a rule from a scoped plugin (such as `foo/some-rule`) without explicitly stating the `@my-organization` scope. This was a bug because it could lead to ambiguous rule references if there was also an unscoped plugin called `eslint-plugin-foo` loaded at the same time. To avoid this ambiguity, in 4.0 references to scoped plugins must include the scope. The config from above should be fixed to: ``` { "plugins": [ "@my-organization/foo" ], "rules": { "@my-organization/foo/some-rule": "error" } } ``` **To address:** If you reference a scoped NPM package as a plugin in a config file, be sure to include the scope wherever you reference it. `RuleTester` now validates properties of test cases ---------------------------------------------------- Starting in 4.0, the `RuleTester` utility will validate properties of test case objects, and an error will be thrown if an unknown property is encountered. This change was added because we found that it was relatively common for developers to make typos in rule tests, often invalidating the assertions that the test cases were trying to make. **To address:** If your tests for custom rules have extra properties, you should remove those properties. AST Nodes no longer have comment properties --------------------------------------------- Prior to 4.0, ESLint required parsers to implement comment attachment, a process where AST nodes would gain additional properties corresponding to their leading and trailing comments in the source file. This made it difficult for users to develop custom parsers, because they would have to replicate the confusing comment attachment semantics required by ESLint. In 4.0, we have moved away from the concept of comment attachment and have moved all comment handling logic into ESLint itself. This should make it easier to develop custom parsers, but it also means that AST nodes will no longer have `leadingComments` and `trailingComments` properties. Conceptually, rule authors can now think of comments in the context of tokens rather than AST nodes. **To address:** If you have a custom rule that depends on the `leadingComments` or `trailingComments` properties of an AST node, you can now use `sourceCode.getCommentsBefore()` and `sourceCode.getCommentsAfter()` instead, respectively. Additionally, the `sourceCode` object now also has `sourceCode.getCommentsInside()` (which returns all the comments inside a node), `sourceCode.getAllComments()` (which returns all the comments in the file), and allows comments to be accessed through various other token iterator methods (such as `getTokenBefore()` and `getTokenAfter()`) with the `{ includeComments: true }` option. For rule authors concerned about supporting ESLint v3.0 in addition to v4.0, the now deprecated `sourceCode.getComments()` is still available and will work for both versions. Finally, please note that the following `SourceCode` methods have been deprecated and will be removed in a future version of ESLint: * `getComments()` - replaced by `getCommentsBefore()`, `getCommentsAfter()`, and `getCommentsInside()` * `getTokenOrCommentBefore()` - replaced by `getTokenBefore()` with the `{ includeComments: true }` option * `getTokenOrCommentAfter()` - replaced by `getTokenAfter()` with the `{ includeComments: true }` option `LineComment` and `BlockComment` events will no longer be emitted during AST traversal --------------------------------------------------------------------------------------- Starting in 4.0, `LineComment` and `BlockComments` events will not be emitted during AST traversal. There are two reasons for this: * This behavior was relying on comment attachment happening at the parser level, which does not happen anymore, to ensure that all comments would be accounted for * Thinking of comments in the context of tokens is more predictable and easier to reason about than thinking about comment tokens in the context of AST nodes **To address:** Instead of relying on `LineComment` and `BlockComment`, rules can now use `sourceCode.getAllComments()` to get all comments in a file. To check all comments of a specific type, rules can use the following pattern: ``` sourceCode.getAllComments().filter(comment => comment.type === "Line"); sourceCode.getAllComments().filter(comment => comment.type === "Block"); ``` Shebangs are now returned from comment APIs --------------------------------------------- Prior to 4.0, shebang comments in a source file would not appear in the output of `sourceCode.getAllComments()` or `sourceCode.getComments()`, but they would appear in the output of `sourceCode.getTokenOrCommentBefore` as line comments. This inconsistency led to some confusion for rule developers. In 4.0, shebang comments are treated as comment tokens of type `Shebang` and will be returned by any `SourceCode` method that returns comments. The goal of this change is to make working with shebang comments more consistent with how other tokens are handled. **To address:** If you have a custom rule that performs operations on comments, some additional logic might be required to ensure that shebang comments are correctly handled or filtered out: ``` sourceCode.getAllComments().filter(comment => comment.type !== "Shebang"); ``` The `global` property in the `linter.verify()` API is no longer supported --------------------------------------------------------------------------- Previously, the `linter.verify()` API accepted a `global` config option, which was a synonym for the documented `globals` property. The `global` option was never documented or officially supported, and did not work in config files. It has been removed in 4.0. **To address:** If you were using the `global` property, please use the `globals` property instead, which does the same thing. More report messages now have full location ranges ---------------------------------------------------- Starting in 3.1.0, rules have been able to specify the *end* location of a reported problem, in addition to the start location, by explicitly specifying an end location in the `report` call. This is useful for tools like editor integrations, which can use the range to precisely display where a reported problem occurs. Starting in 4.0, if a *node* is reported rather than a location, the end location of the range will automatically be inferred from the end location of the node. As a result, many more reported problems will have end locations. This is not expected to cause breakage. However, it will likely result in larger report locations than before. For example, if a rule reports the root node of the AST, the reported problem’s range will be the entire program. In some integrations, this could result in a poor user experience (e.g. if the entire program is highlighted to indicate an error). **To address:** If you have an integration that deals with the ranges of reported problems, make sure you handle large report ranges in a user-friendly way. Some exposed APIs are now ES2015 classes ------------------------------------------ The `CLIEngine`, `SourceCode`, and `RuleTester` modules from ESLint’s Node.js API are now ES2015 classes. This will not break any documented behavior, but it does have some observable effects (for example, the methods on `CLIEngine.prototype` are now non-enumerable). **To address:** If you rely on enumerating the methods of ESLint’s Node.js APIs, use a function that can also access non-enumerable properties such as `Object.getOwnPropertyNames`.
programming_docs
eslint Migrating to v5.0.0 Migrating to v5.0.0 =================== ESLint v5.0.0 is the fifth major version release. We have made a few breaking changes in this release, but we expect that most users will be able to upgrade without any modifications to their build. This guide is intended to walk you through the breaking changes. The lists below are ordered roughly by the number of users each change is expected to affect, where the first items are expected to affect the most users. Breaking changes for users -------------------------- 1. [Node.js 4 is no longer supported](#drop-node-4) 2. [New rules have been added to `eslint:recommended`](#eslint-recommended-changes) 3. [The `experimentalObjectRestSpread` option has been deprecated](#experimental-object-rest-spread) 4. [Linting nonexistent files from the command line is now a fatal error](#nonexistent-files) 5. [The default options for some rules have changed](#rule-default-changes) 6. [Deprecated globals have been removed from the `node`, `browser`, and `jest` environments](#deprecated-globals) 7. [Empty files are now linted](#empty-files) 8. [Plugins in scoped packages are now resolvable in configs](#scoped-plugins) 9. [Multi-line `eslint-disable-line` directives are now reported as problems](#multiline-directives) Breaking changes for plugin/custom rule developers -------------------------------------------------- 1. [The `parent` property of AST nodes is now set before rules start running](#parent-before-rules) 2. [When using the default parser, spread operators now have type `SpreadElement`](#spread-operators) 3. [When using the default parser, rest operators now have type `RestElement`](#rest-operators) 4. [When using the default parser, text nodes in JSX elements now have type `JSXText`](#jsx-text-nodes) 5. [The `context.getScope()` method now returns more proper scopes](#context-get-scope) 6. [The `_linter` property on rule context objects has been removed](#no-context-linter) 7. [`RuleTester` now uses strict equality checks in its assertions](#rule-tester-equality) 8. [Rules are now required to provide messages along with reports](#required-report-messages) Breaking changes for integration developers ------------------------------------------- 1. [The `source` property is no longer available on individual linting messages](#source-property) 2. [Fatal errors now result in an exit code of 2](#exit-code-two) 3. [The `eslint.linter` property is now non-enumerable](#non-enumerable-linter) Node.js 4 is no longer supported ---------------------------------- As of April 30th, 2018, Node.js 4 will be at EOL and will no longer be receiving security updates. As a result, we have decided to drop support for it in ESLint v5. We now support the following versions of Node.js: * Node.js 6 (6.14.0 and above) * Node.js 8 (8.10.0 and above) * Anything above Node.js 9.10.0 **To address:** Make sure you upgrade to at least Node.js 6 when using ESLint v5. If you are unable to upgrade, we recommend continuing to use ESLint v4.x until you are able to upgrade Node.js. `eslint:recommended` changes ----------------------------- Two new rules have been added to the [`eslint:recommended`](migrating-to-5.0.0configuring#using-eslintrecommended) config: * [`for-direction`](migrating-to-5.0.0../rules/for-direction) enforces that a `for` loop update clause moves the counter in the right direction. * [`getter-return`](migrating-to-5.0.0../rules/getter-return) enforces that a `return` statement is present in property getters. **To address:** To mimic the `eslint:recommended` behavior from 4.x, you can disable these rules in a config file: ``` { "extends": "eslint:recommended", "rules": { "for-direction": "off", "getter-return": "off" } } ``` The `experimentalObjectRestSpread` option has been deprecated --------------------------------------------------------------- Previously, when using the default parser it was possible to use the `experimentalObjectRestSpread` option to enable support for [rest/spread properties](https://developers.google.com/web/updates/2017/06/object-rest-spread), as follows: ``` { "parserOptions": { "ecmaFeatures": { "experimentalObjectRestSpread": true } } } ``` Object rest/spread is now an official part of the JavaScript language, so our support for it is no longer experimental. In both ESLint v4 and ESLint v5, object rest/spread can now be enabled with the `"ecmaVersion": 2018` option: ``` { "parserOptions": { "ecmaVersion": 2018 } } ``` Note that this also enables parsing for other features from ES2018, such as [async iteration](https://github.com/tc39/proposal-async-iteration). When using ESLint v5 with the default parser, it is no longer possible to toggle syntax support for object rest/spread independently of other features. For compatibility, ESLint v5 will treat `ecmaFeatures: { experimentalObjectRestSpread: true }` as an alias for `ecmaVersion: 2018` when the former is found in a config file. As a result, if you use object rest/spread, your code should still parse successfully with ESLint v5. However, note that this alias will be removed in ESLint v6. **To address:** If you use the `experimentalObjectRestSpread` option, you should be able to upgrade to ESLint v5 without any changes, but you will encounter a deprecation warning. To avoid the warning, use `ecmaVersion: 2018` in your config file rather than `ecmaFeatures: { experimentalObjectRestSpread: true }`. If you would like to disallow the use of other ES2018 features, consider using rules such as [`no-restricted-syntax`](migrating-to-5.0.0../rules/no-restricted-syntax). Linting nonexistent files from the command line is now a fatal error ---------------------------------------------------------------------- Previous versions of ESLint silently ignored any nonexistent files and globs provided on the command line: ``` eslint nonexistent-file.js 'nonexistent-folder/\*\*/\*.js' # exits without any errors in ESLint v4 ``` Many users found this behavior confusing, because if they made a typo in a filename, ESLint would appear to lint that file successfully while actually not linting anything. ESLint v5 will report a fatal error when either of the following conditions is met: * A file provided on the command line does not exist * A glob or folder provided on the command line does not match any lintable files Note that this also affects the [`CLIEngine.executeOnFiles()`](migrating-to-5.0.0../developer-guide/nodejs-api#cliengineexecuteonfiles) API. **To address:** If you encounter an error about missing files after upgrading to ESLint v5, you may want to double-check that there are no typos in the paths you provide to ESLint. To make the error go away, you can simply remove the given files or globs from the list of arguments provided to ESLint on the command line. If you use a boilerplate generator that relies on this behavior (e.g. to generate a script that runs `eslint tests/` in a new project before any test files are actually present), you can work around this issue by adding a dummy file that matches the given pattern (e.g. an empty `tests/index.js` file). The default options for some rules have changed ------------------------------------------------- * The default options for the [`object-curly-newline`](migrating-to-5.0.0../rules/object-curly-newline) rule have changed from `{ multiline: true }` to `{ consistent: true }`. * The default options object for the [`no-self-assign`](migrating-to-5.0.0../rules/no-self-assign) rule has changed from `{ props: false }` to `{ props: true }`. **To address:** To restore the rule behavior from ESLint v4, you can update your config file to include the previous options: ``` { "rules": { "object-curly-newline": ["error", { "multiline": true }], "no-self-assign": ["error", { "props": false }] } } ``` Deprecated globals have been removed from the `node`, `browser`, and `jest` environments ------------------------------------------------------------------------------------------ Some global variables have been deprecated or removed for code running in Node.js, browsers, and Jest. (For example, browsers used to expose an `SVGAltGlyphElement` global variable to JavaScript code, but this global has been removed from web standards and is no longer present in browsers.) As a result, we have removed these globals from the corresponding `eslint` environments, so use of these globals will trigger an error when using rules such as [`no-undef`](migrating-to-5.0.0../rules/no-undef). **To address:** If you use deprecated globals in the `node`, `browser`, or `jest` environments, you can add a `globals` section to your configuration to re-enable any globals you need. For example: ``` { "env": { "browser": true }, "globals": { "SVGAltGlyphElement": false } } ``` Empty files are now linted ---------------------------- ESLint v4 had a special behavior when linting files that only contain whitespace: it would skip running the parser and rules, and it would always return zero errors. This led to some confusion for users and rule authors, particularly when writing tests for rules. (When writing a stylistic rule, rule authors would occasionally write a test where the source code only contained whitespace, to ensure that the rule behaved correctly when no applicable code was found. However, a test like this would actually not run the rule at all, so an aspect of the rule would end up untested.) ESLint v5 treats whitespace-only files the same way as all other files: it parses them and runs enabled rules on them as appropriate. This could lead to additional linting problems if you use a custom rule that reports errors on empty files. **To address:** If you have an empty file in your project and you don’t want it to be linted, consider adding it to an [`.eslintignore` file](migrating-to-5.0.0configuring#ignoring-files-and-directories). If you have a custom rule, you should make sure it handles empty files appropriately. (In most cases, no changes should be necessary.) Plugins in scoped packages are now resolvable in configs ---------------------------------------------------------- When ESLint v5 encounters a plugin name in a config starting with `@`, the plugin will be resolved as a [scoped npm package](https://docs.npmjs.com/misc/scope). For example, if a config contains `"plugins": ["@foo"]`, ESLint v5 will attempt to load a package called `@foo/eslint-plugin`. (On the other hand, ESLint v4 would attempt to load a package called `eslint-plugin-@foo`.) This is a breaking change because users might have been relying on ESLint finding a package at `node_modules/eslint-plugin-@foo`. However, we think it is unlikely that many users were relying on this behavior, because packages published to npm cannot contain an `@` character in the middle. **To address:** If you rely on ESLint loading a package like `eslint-config-@foo`, consider renaming the package to something else. Multi-line `eslint-disable-line` directives are now reported as problems -------------------------------------------------------------------------- `eslint-disable-line` and `eslint-disable-next-line` directive comments are only allowed to span a single line. For example, the following directive comment is invalid: ``` alert('foo'); /\* eslint-disable-line no-alert \*/ alert('bar'); // (which line is the rule disabled on?) ``` Previously, ESLint would ignore these malformed directive comments. ESLint v5 will report an error when it sees a problem like this, so that the issue can be more easily corrected. **To address:** If you see new reported errors as a result of this change, ensure that your `eslint-disable-line` directives only span a single line. Note that “block comments” (delimited by `/* */`) are still allowed to be used for directives, provided that the block comments do not contain linebreaks. The `parent` property of AST nodes is now set before rules start running -------------------------------------------------------------------------- Previously, ESLint would set the `parent` property on each AST node immediately before running rule listeners for that node. This caused some confusion for rule authors, because the `parent` property would not initially be present on any nodes, and it was sometimes necessary to complicate the structure of a rule to ensure that the `parent` property of a given node would be available when needed. In ESLint v5, the `parent` property is set on all AST nodes before any rules have access to the AST. This makes it easier to write some rules, because the `parent` property is always available rather than being mutated behind the scenes. However, as a side-effect of having `parent` properties, the AST object has a circular structure the first time a rule sees it (previously, it only had a circular structure after the first rule listeners were called). As a result, a custom rule that enumerates all properties of a node in order to traverse the AST might now loop forever or run out of memory if it does not check for cycles properly. **To address:** If you have written a custom rule that enumerates all properties of an AST node, consider excluding the `parent` property or implementing cycle detection to ensure that you obtain the correct result. When using the default parser, spread operators now have type `SpreadElement` ------------------------------------------------------------------------------- Previously, when parsing JS code like `const foo = {...data}` with the `experimentalObjectRestSpread` option enabled, the default parser would generate an `ExperimentalSpreadProperty` node type for the `...data` spread element. In ESLint v5, the default parser will now always give the `...data` AST node the `SpreadElement` type, even if the (now deprecated) [`experimentalObjectRestSpread`](#experimental-object-rest-spread) option is enabled. This makes the AST compliant with the current ESTree spec. **To address:** If you have written a custom rule that relies on spread operators having the `ExperimentalSpreadProperty` type, you should update it to also work with spread operators that have the `SpreadElement` type. When using the default parser, rest operators now have type `RestElement` --------------------------------------------------------------------------- Previously, when parsing JS code like `const {foo, ...rest} = data` with the `experimentalObjectRestSpread` option enabled, the default parser would generate an `ExperimentalRestProperty` node type for the `...data` rest element. In ESLint v5, the default parser will now always give the `...data` AST node the `RestElement` type, even if the (now deprecated) [`experimentalObjectRestSpread`](#experimental-object-rest-spread) option is enabled. This makes the AST compliant with the current ESTree spec. **To address:** If you have written a custom rule that relies on rest operators having the `ExperimentalRestProperty` type, you should update it to also work with rest operators that have the `RestElement` type. When using the default parser, text nodes in JSX elements now have type `JSXText` ----------------------------------------------------------------------------------- When parsing JSX code like `<a>foo</a>`, the default parser will now give the `foo` AST node the `JSXText` type, rather than the `Literal` type. This makes the AST compliant with a recent update to the JSX spec. **To address:** If you have written a custom rule that relies on text nodes in JSX elements having the `Literal` type, you should update it to also work with nodes that have the `JSXText` type. The `context.getScope()` method now returns more proper scopes ---------------------------------------------------------------- Previously, the `context.getScope()` method changed its behavior based on the `parserOptions.ecmaVersion` property. However, this could cause confusing behavior when using a parser that doesn’t respond to the `ecmaVersion` option, such as `babel-eslint`. Additionally, `context.getScope()` incorrectly returned the parent scope of the proper scope on `CatchClause` (in ES5), `ForStatement` (in ≧ES2015), `ForInStatement` (in ≧ES2015), `ForOfStatement`, and `WithStatement` nodes. In ESLint v5, the `context.getScope()` method has the same behavior regardless of `parserOptions.ecmaVersion` and returns the proper scope. See [the documentation](migrating-to-5.0.0../developer-guide/working-with-rules#contextgetscope) for more details on which scopes are returned. **To address:** If you have written a custom rule that uses the `context.getScope()` method in node handlers, you may need to update it to account for the modified scope information. The `_linter` property on rule context objects has been removed ----------------------------------------------------------------- Previously, rule context objects had an undocumented `_linter` property, which was used internally within ESLint to process reports from rules. Some rules used this property to achieve functionality that was not intended to be possible for rules. For example, several plugins used the `_linter` property in a rule to monitor reports from other rules, for the purpose of checking for unused `/* eslint-disable */` directive comments. Although this functionality was useful for users, it could also cause stability problems for projects using ESLint. For example, an upgrade to a rule in one plugin could unexpectedly cause a rule in another plugin to start reporting errors. The `_linter` property has been removed in ESLint v5.0, so it is no longer possible to implement rules with this functionality. However, the [`--report-unused-disable-directives`](migrating-to-5.0.0command-line-interface#--report-unused-disable-directives) CLI flag can be used to flag unused directive comments. `RuleTester` now uses strict equality checks in its assertions --------------------------------------------------------------- Previously, `RuleTester` used loose equality when making some of its assertions. For example, if a rule produced the string `"7"` as a result of autofixing, `RuleTester` would allow the number `7` in an `output` assertion, rather than the string `"7"`. In ESLint v5, comparisons from `RuleTester` use strict equality, so an assertion like this will no longer pass. **To address:** If you use `RuleTester` to write tests for your custom rules, make sure the expected values in your assertions are strictly equal to the actual values. Rules are now required to provide messages along with reports --------------------------------------------------------------- Previously, it was possible for rules to report AST nodes without providing a report message. This was not intended behavior, and as a result the default formatter would crash if a rule omitted a message. However, it was possible to avoid a crash when using a non-default formatter, such as `json`. In ESLint v5, reporting a problem without providing a message always results in an error. **To address:** If you have written a custom rule that reports a problem without providing a message, update it to provide a message along with the report. The `source` property is no longer available on individual linting messages ----------------------------------------------------------------------------- As announced in [October 2016](https://eslint.org/blog/2016/10/eslint-v3.8.0-released#additional-property-on-linting-results), the `source` property has been removed from individual lint message objects. **To address:** If you have a formatter or integration which relies on using the `source` property on individual linting messages, you should update it to use the `source` property on file results objects instead. Fatal errors now result in an exit code of 2 ---------------------------------------------- When using ESLint v4, both of the following scenarios resulted in an exit code of 1 when running ESLint on the command line: * Linting completed successfully, but there are some linting errors * Linting was unsuccessful due to a fatal error (e.g. an invalid config file) As a result, it was difficult for an integration to distinguish between the two cases to determine whether it should try to extract linting results from the output. In ESLint v5, an unsuccessful linting run due to a fatal error will result in an exit code of 2, rather than 1. **To address:** If you have an integration that detects all problems with linting runs by checking whether the exit code is equal to 1, update it to check whether the exit code is nonzero instead. The `eslint.linter` property is now non-enumerable ---------------------------------------------------- When using ESLint’s Node.js API, the [`linter`](migrating-to-5.0.0../developer-guide/nodejs-api#linter-1) property is now non-enumerable. Note that the `linter` property was deprecated in ESLint v4 in favor of the [`Linter`](migrating-to-5.0.0../developer-guide/nodejs-api#linter) property. **To address:** If you rely on enumerating all the properties of the `eslint` object, use something like `Object.getOwnPropertyNames` to ensure that non-enumerable keys are captured.
programming_docs
eslint Command Line Interface Command Line Interface ====================== The ESLint Command Line Interface (CLI) lets you execute linting from the terminal. The CLI has a variety of options that you can pass to configure ESLint. Run the CLI ----------- ESLint requires Node.js for installation. Follow the instructions in the [Getting Started Guide](command-line-interfacegetting-started) to install ESLint. Most users use [`npx`](https://docs.npmjs.com/cli/v8/commands/npx) to run ESLint on the command line like this: ``` npx eslint [options] [file|dir|glob]* ``` Such as: ``` # Run on two files npx eslint file1.js file2.js # Run on multiple files npx eslint lib/** ``` Please note that when passing a glob as a parameter, it is expanded by your shell. The results of the expansion can vary depending on your shell, and its configuration. If you want to use node `glob` syntax, you have to quote your parameter (using double quotes if you need it to run in Windows), as follows: ``` npx eslint "lib/\*\*" ``` **Note:** You can also use alternative package managers such as [Yarn](https://yarnpkg.com/) or [pnpm](https://pnpm.io/) to run ESLint. Please refer to your package manager’s documentation for the correct syntax. Pass Multiple Values to an Option --------------------------------- Options that accept multiple values can be specified by repeating the option or with a comma-delimited list (other than [`--ignore-pattern`](#--ignore-pattern), which does not allow the second style). Examples of options that accept multiple values: ``` npx eslint --ext .jsx --ext .js lib/ # OR npx eslint --ext .jsx,.js lib/ ``` Options ------- You can view all the CLI options by running `npx eslint -h`. ``` eslint [options] file.js [file.js] [dir] Basic configuration: --no-eslintrc Disable use of configuration from .eslintrc.* -c, --config path::String Use this configuration, overriding .eslintrc.* config options if present --env [String] Specify environments --ext [String] Specify JavaScript file extensions --global [String] Define global variables --parser String Specify the parser to be used --parser-options Object Specify parser options --resolve-plugins-relative-to path::String A folder where plugins should be resolved from, CWD by default Specify rules and plugins: --plugin [String] Specify plugins --rule Object Specify rules --rulesdir [path::String] Load additional rules from this directory. Deprecated: Use rules from plugins Fix problems: --fix Automatically fix problems --fix-dry-run Automatically fix problems without saving the changes to the file system --fix-type Array Specify the types of fixes to apply (directive, problem, suggestion, layout) Ignore files: --ignore-path path::String Specify path of ignore file --no-ignore Disable use of ignore files and patterns --ignore-pattern [String] Pattern of files to ignore (in addition to those in .eslintignore) Use stdin: --stdin Lint code provided on <STDIN> - default: false --stdin-filename String Specify filename to process STDIN as Handle warnings: --quiet Report errors only - default: false --max-warnings Int Number of warnings to trigger nonzero exit code - default: -1 Output: -o, --output-file path::String Specify file to write report to -f, --format String Use a specific output format - default: stylish --color, --no-color Force enabling/disabling of color Inline configuration comments: --no-inline-config Prevent comments from changing config or rules --report-unused-disable-directives Adds reported errors for unused eslint-disable directives Caching: --cache Only check changed files - default: false --cache-file path::String Path to the cache file. Deprecated: use --cache-location - default: .eslintcache --cache-location path::String Path to the cache file or directory --cache-strategy String Strategy to use for detecting changed files in the cache - either: metadata or content - default: metadata Miscellaneous: --init Run config initialization wizard - default: false --env-info Output execution environment information - default: false --no-error-on-unmatched-pattern Prevent errors when pattern is unmatched --exit-on-fatal-error Exit with exit code 2 in case of fatal error - default: false --debug Output debugging information -h, --help Show help -v, --version Output the version number --print-config path::String Print the configuration for the given file ``` ### Basic Configuration #### `--no-eslintrc` Disables use of configuration from `.eslintrc.*` and `package.json` files. * **Argument Type**: No argument. ##### `--no-eslintrc` example ``` npx eslint --no-eslintrc file.js ``` #### `-c`, `--config` This option allows you to specify an additional configuration file for ESLint (see [Configuring ESLint](command-line-interfaceconfiguring/index) for more). * **Argument Type**: String. Path to file. * **Multiple Arguments**: No ##### `-c`, `--config` example ``` npx eslint -c ~/my-eslint.json file.js ``` This example uses the configuration file at `~/my-eslint.json`. If `.eslintrc.*` and/or `package.json` files are also used for configuration (i.e., `--no-eslintrc` was not specified), the configurations are merged. Options from this configuration file have precedence over the options from `.eslintrc.*` and `package.json` files. #### `--env` This option enables specific environments. * **Argument Type**: String. One of the available environments. * **Multiple Arguments**: Yes Details about the global variables defined by each environment are available in the [Specifying Environments](command-line-interfaceconfiguring/language-options#specifying-environments) documentation. This option only enables environments. It does not disable environments set in other configuration files. To specify multiple environments, separate them using commas, or use the option multiple times. ##### `--env` example ``` npx eslint --env browser,node file.js npx eslint --env browser --env node file.js ``` #### `--ext` This option allows you to specify which file extensions ESLint uses when searching for target files in the directories you specify. * **Argument Type**: String. File extension. * **Multiple Arguments**: Yes * **Default Value**: `.js` and the files that match the `overrides` entries of your configuration. `--ext` is only used when the the patterns to lint are directories. If you use glob patterns or file names, then `--ext` is ignored. For example, `npx eslint "lib/*" --ext .js` matches all files within the `lib/` directory, regardless of extension. ##### `--ext` example ``` # Use only .ts extension npx eslint . --ext .ts # Use both .js and .ts npx eslint . --ext .js --ext .ts # Also use both .js and .ts npx eslint . --ext .js,.ts ``` #### `--global` This option defines global variables so that they are not flagged as undefined by the [`no-undef`](command-line-interface../rules/no-undef) rule. * **Argument Type**: String. Name of the global variable. Any specified global variables are assumed to be read-only by default, but appending `:true` to a variable’s name ensures that `no-undef` also allows writes. * **Multiple Arguments**: Yes ##### `--global` example ``` npx eslint --global require,exports:true file.js npx eslint --global require --global exports:true ``` #### `--parser` This option allows you to specify a parser to be used by ESLint. * **Argument Type**: String. Parser to be used by ESLint. * **Multiple Arguments**: No * **Default Value**: `espree` ##### `--parser` example ``` # Use TypeScript ESLint parser npx eslint --parser @typescript-eslint/parser file.ts ``` #### `--parser-options` This option allows you to specify parser options to be used by ESLint. The available parser options are determined by the parser being used. * **Argument Type**: Key/value pair separated by colon (`:`). * **Multiple Arguments**: Yes ##### `--parser-options` example ``` echo '3 \*\* 4' | npx eslint --stdin --parser-options ecmaVersion:6 # fails with a parsing error echo '3 \*\* 4' | npx eslint --stdin --parser-options ecmaVersion:7 # succeeds, yay! ``` #### `--resolve-plugins-relative-to` Changes the directory where plugins are resolved from. * **Argument Type**: String. Path to directory. * **Multiple Arguments**: No * **Default Value**: By default, plugins are resolved from the directory in which your configuration file is found. This option should be used when plugins were installed by someone other than the end user. It should be set to the project directory of the project that has a dependency on the necessary plugins. For example: * When using a config file that is located outside of the current project (with the `--config` flag), if the config uses plugins which are installed locally to itself, `--resolve-plugins-relative-to` should be set to the directory containing the config file. * If an integration has dependencies on ESLint and a set of plugins, and the tool invokes ESLint on behalf of the user with a preset configuration, the tool should set `--resolve-plugins-relative-to` to the top-level directory of the tool. ##### `--resolve-plugins-relative-to` example ``` npx eslint --config ~/personal-eslintrc.js \ --resolve-plugins-relative-to /usr/local/lib/ ``` ### Specify Rules and Plugins #### `--plugin` This option specifies a plugin to load. * **Argument Type**: String. Plugin name. You can optionally omit the prefix `eslint-plugin-` from the plugin name. * **Multiple Arguments**: Yes Before using the plugin, you have to install it using npm. ##### `--plugin` example ``` npx eslint --plugin jquery file.js npx eslint --plugin eslint-plugin-mocha file.js ``` #### `--rule` This option specifies the rules to be used. * **Argument Type**: Rules and their configuration specified with [levn](https://github.com/gkz/levn#levn--) format. * **Multiple Arguments**: Yes These rules are merged with any rules specified with configuration files. If the rule is defined in a plugin, you have to prefix the rule ID with the plugin name and a `/`. To ignore rules in `.eslintrc` configuration files and only run rules specified in the command line, use the `--rules` flag in combination with the [`--no-eslintrc`](#--no-eslintrc) flag. ##### `--rule` example ``` # Apply single rule npx eslint --rule 'quotes: [error, double]' # Apply multiple rules npx eslint --rule 'guard-for-in: error' --rule 'brace-style: [error, 1tbs]' # Apply rule from jquery plugin npx eslint --rule 'jquery/dollar-sign: error' # Only apply rule from the command line npx eslint --rule 'quotes: [error, double]' --no-eslintrc ``` #### `--rulesdir` **Deprecated**: Use rules from plugins instead. This option allows you to specify another directory from which to load rules files. This allows you to dynamically load new rules at run time. This is useful when you have custom rules that aren’t suitable for being bundled with ESLint. * **Argument Type**: String. Path to directory. The rules in your custom rules directory must follow the same format as bundled rules to work properly. * **Multiple Arguments**: Yes. Note that, as with core rules and plugin rules, you still need to enable the rules in configuration or via the `--rule` CLI option in order to actually run those rules during linting. Specifying a rules directory with `--rulesdir` does not automatically enable the rules within that directory. ##### `--rulesdir` example ``` npx eslint --rulesdir my-rules/ file.js npx eslint --rulesdir my-rules/ --rulesdir my-other-rules/ file.js ``` ### Fix Problems #### `--fix` This option instructs ESLint to try to fix as many issues as possible. The fixes are made to the actual files themselves and only the remaining unfixed issues are output. * **Argument Type**: No argument. Not all problems are fixable using this option, and the option does not work in these situations: 1. This option throws an error when code is piped to ESLint. 2. This option has no effect on code that uses a processor, unless the processor opts into allowing autofixes. If you want to fix code from `stdin` or otherwise want to get the fixes without actually writing them to the file, use the [`--fix-dry-run`](#--fix-dry-run) option. ##### `--fix` example ``` npx eslint --fix file.js ``` #### `--fix-dry-run` This option has the same effect as `--fix` with the difference that the fixes are not saved to the file system. Because the default formatter does not output the fixed code, you’ll have to use another formatter (e.g. `--format json`) to get the fixes. * **Argument Type**: No argument. This makes it possible to fix code from `stdin` when used with the `--stdin` flag. This flag can be useful for integrations (e.g. editor plugins) which need to autofix text from the command line without saving it to the filesystem. ##### `--fix-dry-run` example ``` getSomeText | npx eslint --stdin --fix-dry-run --format json ``` #### `--fix-type` This option allows you to specify the type of fixes to apply when using either `--fix` or `--fix-dry-run`. * **Argument Type**: String. One of the following fix types: 1. `problem` - fix potential errors in the code 2. `suggestion` - apply fixes to the code that improve it 3. `layout` - apply fixes that do not change the program structure (AST) 4. `directive` - apply fixes to inline directives such as `// eslint-disable` * **Multiple Arguments**: Yes This option is helpful if you are using another program to format your code, but you would still like ESLint to apply other types of fixes. ##### `--fix-type` example ``` npx eslint --fix --fix-type suggestion . npx eslint --fix --fix-type suggestion --fix-type problem . npx eslint --fix --fix-type suggestion,layout . ``` ### Ignore Files #### `--ignore-path` This option allows you to specify the file to use as your `.eslintignore`. * **Argument Type**: String. Path to file. * **Multiple Arguments**: No * **Default Value**: By default, ESLint looks for `.eslintignore` in the current working directory. **Note:** `--ignore-path` is not supported when using [flat configuration](command-line-interface./configuring/configuration-files-new) (`eslint.config.js`). ##### `--ignore-path` example ``` npx eslint --ignore-path tmp/.eslintignore file.js npx eslint --ignore-path .gitignore file.js ``` #### `--no-ignore` Disables excluding of files from `.eslintignore` files, `--ignore-path` flags, `--ignore-pattern` flags, and the `ignorePatterns` property in config files. * **Argument Type**: No argument. ##### `--no-ignore` example ``` npx eslint --no-ignore file.js ``` #### `--ignore-pattern` This option allows you to specify patterns of files to ignore (in addition to those in `.eslintignore`). * **Argument Type**: String. The supported syntax is the same as for [`.eslintignore` files](command-line-interfaceconfiguring/ignoring-code#the-eslintignore-file), which use the same patterns as the [`.gitignore` specification](https://git-scm.com/docs/gitignore). You should quote your patterns in order to avoid shell interpretation of glob patterns. * **Multiple Arguments**: Yes ##### `--ignore-pattern` example ``` npx eslint --ignore-pattern "/lib/" --ignore-pattern "/src/vendor/\*" . ``` ### Use stdin #### `--stdin` This option tells ESLint to read and lint source code from STDIN instead of from files. You can use this to pipe code to ESLint. * **Argument Type**: No argument. ##### `--stdin` example ``` cat myfile.js | npx eslint --stdin ``` #### `--stdin-filename` This option allows you to specify a filename to process STDIN as. * **Argument Type**: String. Path to file. * **Multiple Arguments**: No This is useful when processing files from STDIN and you have rules which depend on the filename. ##### `--stdin-filename` example ``` cat myfile.js | npx eslint --stdin --stdin-filename myfile.js ``` ### Handle Warnings #### `--quiet` This option allows you to disable reporting on warnings. If you enable this option, only errors are reported by ESLint. * **Argument Type**: No argument. ##### `--quiet` example ``` npx eslint --quiet file.js ``` #### `--max-warnings` This option allows you to specify a warning threshold, which can be used to force ESLint to exit with an error status if there are too many warning-level rule violations in your project. * **Argument Type**: Integer. The maximum number of warnings to allow. To prevent this behavior, do not use this option or specify `-1` as the argument. * **Multiple Arguments**: No Normally, if ESLint runs and finds no errors (only warnings), it exits with a success exit status. However, if `--max-warnings` is specified and the total warning count is greater than the specified threshold, ESLint exits with an error status. ##### `--max-warnings` example ``` npx eslint --max-warnings 10 file.js ``` ### Output #### `-o`, `--output-file` Write the output of linting results to a specified file. * **Argument Type**: String. Path to file. * **Multiple Arguments**: No ##### `-o`, `--output-file` example ``` npx eslint -o ./test/test.html ``` #### `-f`, `--format` This option specifies the output format for the console. * **Argument Type**: String. One of the [built-in formatters](command-line-interfaceformatters/index) or a custom formatter. * **Multiple Arguments**: No * **Default Value**: [`stylish`](command-line-interfaceformatters/index#stylish) If you are using a custom formatter defined in a local file, you can specify the path to the custom formatter file. An npm-installed formatter is resolved with or without `eslint-formatter-` prefix. When specified, the given format is output to the console. If you’d like to save that output into a file, you can do so on the command line like so: ``` # Saves the output into the `results.txt` file. npx eslint -f compact file.js > results.txt ``` ##### `-f`, `--format` example Use the built-in `compact` formatter: ``` npx eslint --format compact file.js ``` Use a local custom formatter: ``` npx eslint -f ./customformat.js file.js ``` Use an npm-installed formatter: ``` npm install eslint-formatter-pretty # Then run one of the following commands npx eslint -f pretty file.js # or alternatively npx eslint -f eslint-formatter-pretty file.js ``` #### `--color` and `--no-color` These options force the enabling/disabling of colorized output. * **Argument Type**: No argument. You can use these options to override the default behavior, which is to enable colorized output unless no TTY is detected, such as when piping `eslint` through `cat` or `less`. ##### `--color` and `--no-color` example ``` npx eslint --color file.js | cat npx eslint --no-color file.js ``` ### Inline Configuration Comments #### `--no-inline-config` This option prevents inline comments like `/*eslint-disable*/` or `/*global foo*/` from having any effect. * **Argument Type**: No argument. This allows you to set an ESLint config without files modifying it. All inline config comments are ignored, such as: * `/*eslint-disable*/` * `/*eslint-enable*/` * `/*global*/` * `/*eslint*/` * `/*eslint-env*/` * `// eslint-disable-line` * `// eslint-disable-next-line` ##### `--no-inline-config` example ``` npx eslint --no-inline-config file.js ``` #### `--report-unused-disable-directives` This option causes ESLint to report directive comments like `// eslint-disable-line` when no errors would have been reported on that line anyway. * **Argument Type**: No argument. This can be useful to prevent future errors from unexpectedly being suppressed, by cleaning up old `eslint-disable` comments which are no longer applicable. ##### `--report-unused-disable-directives` example ``` npx eslint --report-unused-disable-directives file.js ``` ### Caching #### `--cache` Store the info about processed files in order to only operate on the changed ones. Enabling this option can dramatically improve ESLint’s run time performance by ensuring that only changed files are linted. The cache is stored in `.eslintcache` by default. * **Argument Type**: No argument. If you run ESLint with `--cache` and then run ESLint without `--cache`, the `.eslintcache` file will be deleted. This is necessary because the results of the lint might change and make `.eslintcache` invalid. If you want to control when the cache file is deleted, then use `--cache-location` to specify an alternate location for the cache file. Autofixed files are not placed in the cache. Subsequent linting that does not trigger an autofix will place it in the cache. ##### `--cache` example ``` npx eslint --cache file.js ``` #### `--cache-file` **Deprecated**: Use `--cache-location` instead. Path to the cache file. If none specified `.eslintcache` is used. The file is created in the directory where the `eslint` command is executed. #### `--cache-location` Specify the path to the cache location. Can be a file or a directory. * **Argument Type**: String. Path to file or directory. If a directory is specified, a cache file is created inside the specified folder. The name of the file is based on the hash of the current working directory, e.g.: `.cache_hashOfCWD`. * **Multiple Arguments**: No * **Default Value**: If no location is specified, `.eslintcache` is used. The file is created in the directory where the `eslint` command is executed. If the directory for the cache does not exist make sure you add a trailing `/` on \*nix systems or `\` on Windows. Otherwise, the path is assumed to be a file. ##### `--cache-location` example ``` npx eslint "src/\*\*/\*.js" --cache --cache-location "/Users/user/.eslintcache/" ``` #### `--cache-strategy` Strategy for the cache to use for detecting changed files. * **Argument Type**: String. One of the following values: 1. `metadata` 2. `content` * **Multiple Arguments**: No * **Default Value**: `metadata` The `content` strategy can be useful in cases where the modification time of your files changes even if their contents have not. For example, this can happen during git operations like `git clone` because git does not track file modification time. ##### `--cache-strategy` example ``` npx eslint "src/\*\*/\*.js" --cache --cache-strategy content ``` ### Miscellaneous #### `--init` This option runs `npm init @eslint/config` to start the config initialization wizard. It’s designed to help new users quickly create an `.eslintrc` file by answering a few questions. When you use this flag, the CLI does not perform linting. * **Argument Type**: No argument. The resulting configuration file is created in the current directory. ##### `--init` example ``` npx eslint --init ``` #### `--env-info` This option outputs information about the execution environment, including the version of Node.js, npm, and local and global installations of ESLint. * **Argument Type**: No argument. The ESLint team may ask for this information to help solve bugs. When you use this flag, the CLI does not perform linting. ##### `--env-info` example ``` npx eslint --env-info ``` #### `--no-error-on-unmatched-pattern` This option prevents errors when a quoted glob pattern or `--ext` is unmatched. This does not prevent errors when your shell can’t match a glob. * **Argument Type**: No argument. ##### `--no-error-on-unmatched-pattern` example ``` npx eslint --no-error-on-unmatched-pattern --ext .ts "lib/\*" ``` #### `--exit-on-fatal-error` This option causes ESLint to exit with exit code 2 if one or more fatal parsing errors occur. Without this option, ESLint reports fatal parsing errors as rule violations. * **Argument Type**: No argument. ##### `--exit-on-fatal-error` example ``` npx eslint --exit-on-fatal-error file.js ``` #### `--debug` This option outputs debugging information to the console. Add this flag to an ESLint command line invocation in order to get extra debugging information while the command runs. * **Argument Type**: No argument. This information is useful when you’re seeing a problem and having a hard time pinpointing it. The ESLint team may ask for this debugging information to help solve bugs. ##### `--debug` example ``` npx eslint --debug test.js ``` #### `-h`, `--help` This option outputs the help menu, displaying all of the available options. All other options are ignored when this is present. When you use this flag, the CLI does not perform linting. * **Argument Type**: No argument. ##### `-h`, `--help` example ``` npx eslint --help ``` #### `-v`, `--version` This option outputs the current ESLint version onto the console. All other options are ignored when this is present. When you use this flag, the CLI does not perform linting. * **Argument Type**: No argument. ##### `-v`, `--version` example ``` npx eslint --version ``` #### `--print-config` This option outputs the configuration to be used for the file passed. When present, no linting is performed and only config-related options are valid. When you use this flag, the CLI does not perform linting. * **Argument Type**: String. Path to file. * **Multiple Arguments**: No ##### `--print-config` example ``` npx eslint --print-config file.js ``` Exit Codes ---------- When linting files, ESLint exits with one of the following exit codes: * `0`: Linting was successful and there are no linting errors. If the [`--max-warnings`](#--max-warnings) flag is set to `n`, the number of linting warnings is at most `n`. * `1`: Linting was successful and there is at least one linting error, or there are more linting warnings than allowed by the `--max-warnings` option. * `2`: Linting was unsuccessful due to a configuration problem or an internal error.
programming_docs
eslint Rule Deprecation Rule Deprecation ================ Balancing the trade-offs of improving a tool and the frustration these changes can cause is a difficult task. One key area in which this affects our users is in the removal of rules. The ESLint team is committed to making upgrading as easy and painless as possible. To that end, the team has agreed upon the following set of guidelines for deprecating rules in the future. The goal of these guidelines is to allow for improvements and changes to be made without breaking existing configurations. * Rules will never be removed from ESLint. * Rules will be deprecated as needed, and marked as such in all documentation. * After a rule has been deprecated, the team will no longer do any work on it. This includes bug fixes, enhancements, and updates to the rule’s documentation. Issues and pull requests related to deprecated rule will not be accepted and will be closed. Since deprecated rules will never be removed, you can continue to use them indefinitely if they are working for you. However, keep in mind that deprecated rules will effectively be unmaintained. We hope that by following these guidelines we will be able to continue improving and working to make ESLint the best tool it can be while causing as little disruption to our users as possible during the process. eslint Formatters Formatters ========== ESLint comes with several built-in formatters to control the appearance of the linting results, and supports third-party formatters as well. You can specify a formatter using the `--format` or `-f` flag in the CLI. For example, `--format json` uses the `json` formatter. The built-in formatter options are: * [checkstyle](#checkstyle) * [compact](#compact) * [html](#html) * [jslint-xml](#jslint-xml) * [json-with-metadata](#json-with-metadata) * [json](#json) * [junit](#junit) * [stylish](#stylish) * [tap](#tap) * [unix](#unix) * [visualstudio](#visualstudio) Example Source -------------- Examples of each formatter were created from linting `fullOfProblems.js` using the `.eslintrc.json` configuration shown below. `fullOfProblems.js`: ``` function addOne(i) { if (i != NaN) { return i ++ } else { return } }; ``` `.eslintrc.json`: ``` { "extends": "eslint:recommended", "rules": { "consistent-return": 2, "indent" : [1, 4], "no-else-return" : 1, "semi" : [1, "always"], "space-unary-ops" : 2 } } ``` Tests the formatters with the CLI: ``` npx eslint --format <Add formatter here> fullOfProblems.js ``` Built-In Formatter Options -------------------------- ### checkstyle Outputs results to the [Checkstyle](https://checkstyle.sourceforge.io/) format. Example output: ``` &lt;?xml version=&#34;1.0&#34; encoding=&#34;utf-8&#34;?&gt;&lt;checkstyle version=&#34;4.3&#34;&gt;&lt;file name=&#34;/var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems.js&#34;&gt;&lt;error line=&#34;1&#34; column=&#34;10&#34; severity=&#34;error&#34; message=&#34;&amp;apos;addOne&amp;apos; is defined but never used. (no-unused-vars)&#34; source=&#34;eslint.rules.no-unused-vars&#34; /&gt;&lt;error line=&#34;2&#34; column=&#34;9&#34; severity=&#34;error&#34; message=&#34;Use the isNaN function to compare with NaN. (use-isnan)&#34; source=&#34;eslint.rules.use-isnan&#34; /&gt;&lt;error line=&#34;3&#34; column=&#34;16&#34; severity=&#34;error&#34; message=&#34;Unexpected space before unary operator &amp;apos;++&amp;apos;. (space-unary-ops)&#34; source=&#34;eslint.rules.space-unary-ops&#34; /&gt;&lt;error line=&#34;3&#34; column=&#34;20&#34; severity=&#34;warning&#34; message=&#34;Missing semicolon. (semi)&#34; source=&#34;eslint.rules.semi&#34; /&gt;&lt;error line=&#34;4&#34; column=&#34;12&#34; severity=&#34;warning&#34; message=&#34;Unnecessary &amp;apos;else&amp;apos; after &amp;apos;return&amp;apos;. (no-else-return)&#34; source=&#34;eslint.rules.no-else-return&#34; /&gt;&lt;error line=&#34;5&#34; column=&#34;1&#34; severity=&#34;warning&#34; message=&#34;Expected indentation of 8 spaces but found 6. (indent)&#34; source=&#34;eslint.rules.indent&#34; /&gt;&lt;error line=&#34;5&#34; column=&#34;7&#34; severity=&#34;error&#34; message=&#34;Function &amp;apos;addOne&amp;apos; expected a return value. (consistent-return)&#34; source=&#34;eslint.rules.consistent-return&#34; /&gt;&lt;error line=&#34;5&#34; column=&#34;13&#34; severity=&#34;warning&#34; message=&#34;Missing semicolon. (semi)&#34; source=&#34;eslint.rules.semi&#34; /&gt;&lt;error line=&#34;7&#34; column=&#34;2&#34; severity=&#34;error&#34; message=&#34;Unnecessary semicolon. (no-extra-semi)&#34; source=&#34;eslint.rules.no-extra-semi&#34; /&gt;&lt;/file&gt;&lt;/checkstyle&gt; ``` ### compact Human-readable output format. Mimics the default output of JSHint. Example output: ``` /var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems.js: line 1, col 10, Error - &#39;addOne&#39; is defined but never used. (no-unused-vars) /var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems.js: line 2, col 9, Error - Use the isNaN function to compare with NaN. (use-isnan) /var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems.js: line 3, col 16, Error - Unexpected space before unary operator &#39;++&#39;. (space-unary-ops) /var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems.js: line 3, col 20, Warning - Missing semicolon. (semi) /var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems.js: line 4, col 12, Warning - Unnecessary &#39;else&#39; after &#39;return&#39;. (no-else-return) /var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems.js: line 5, col 1, Warning - Expected indentation of 8 spaces but found 6. (indent) /var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems.js: line 5, col 7, Error - Function &#39;addOne&#39; expected a return value. (consistent-return) /var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems.js: line 5, col 13, Warning - Missing semicolon. (semi) /var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems.js: line 7, col 2, Error - Unnecessary semicolon. (no-extra-semi) 9 problems ``` ### html Outputs results to HTML. The `html` formatter is useful for visual presentation in the browser. Example output: ### jslint-xml Outputs results to format compatible with the [JSLint Jenkins plugin](https://plugins.jenkins.io/jslint/). Example output: ``` &lt;?xml version=&#34;1.0&#34; encoding=&#34;utf-8&#34;?&gt;&lt;jslint&gt;&lt;file name=&#34;/var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems.js&#34;&gt;&lt;issue line=&#34;1&#34; char=&#34;10&#34; evidence=&#34;&#34; reason=&#34;&amp;apos;addOne&amp;apos; is defined but never used. (no-unused-vars)&#34; /&gt;&lt;issue line=&#34;2&#34; char=&#34;9&#34; evidence=&#34;&#34; reason=&#34;Use the isNaN function to compare with NaN. (use-isnan)&#34; /&gt;&lt;issue line=&#34;3&#34; char=&#34;16&#34; evidence=&#34;&#34; reason=&#34;Unexpected space before unary operator &amp;apos;++&amp;apos;. (space-unary-ops)&#34; /&gt;&lt;issue line=&#34;3&#34; char=&#34;20&#34; evidence=&#34;&#34; reason=&#34;Missing semicolon. (semi)&#34; /&gt;&lt;issue line=&#34;4&#34; char=&#34;12&#34; evidence=&#34;&#34; reason=&#34;Unnecessary &amp;apos;else&amp;apos; after &amp;apos;return&amp;apos;. (no-else-return)&#34; /&gt;&lt;issue line=&#34;5&#34; char=&#34;1&#34; evidence=&#34;&#34; reason=&#34;Expected indentation of 8 spaces but found 6. (indent)&#34; /&gt;&lt;issue line=&#34;5&#34; char=&#34;7&#34; evidence=&#34;&#34; reason=&#34;Function &amp;apos;addOne&amp;apos; expected a return value. (consistent-return)&#34; /&gt;&lt;issue line=&#34;5&#34; char=&#34;13&#34; evidence=&#34;&#34; reason=&#34;Missing semicolon. (semi)&#34; /&gt;&lt;issue line=&#34;7&#34; char=&#34;2&#34; evidence=&#34;&#34; reason=&#34;Unnecessary semicolon. (no-extra-semi)&#34; /&gt;&lt;/file&gt;&lt;/jslint&gt; ``` ### json-with-metadata Outputs JSON-serialized results. The `json-with-metadata` provides the same linting results as the [`json`](#json) formatter with additional metadata about the rules applied. The linting results are included in the `results` property and the rules metadata is included in the `metadata` property. Alternatively, you can use the [ESLint Node.js API](../../developer-guide/nodejs-api) to programmatically use ESLint. Example output: ``` {&#34;results&#34;:[{&#34;filePath&#34;:&#34;/var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems.js&#34;,&#34;messages&#34;:[{&#34;ruleId&#34;:&#34;no-unused-vars&#34;,&#34;severity&#34;:2,&#34;message&#34;:&#34;&#39;addOne&#39; is defined but never used.&#34;,&#34;line&#34;:1,&#34;column&#34;:10,&#34;nodeType&#34;:&#34;Identifier&#34;,&#34;messageId&#34;:&#34;unusedVar&#34;,&#34;endLine&#34;:1,&#34;endColumn&#34;:16},{&#34;ruleId&#34;:&#34;use-isnan&#34;,&#34;severity&#34;:2,&#34;message&#34;:&#34;Use the isNaN function to compare with NaN.&#34;,&#34;line&#34;:2,&#34;column&#34;:9,&#34;nodeType&#34;:&#34;BinaryExpression&#34;,&#34;messageId&#34;:&#34;comparisonWithNaN&#34;,&#34;endLine&#34;:2,&#34;endColumn&#34;:17},{&#34;ruleId&#34;:&#34;space-unary-ops&#34;,&#34;severity&#34;:2,&#34;message&#34;:&#34;Unexpected space before unary operator &#39;++&#39;.&#34;,&#34;line&#34;:3,&#34;column&#34;:16,&#34;nodeType&#34;:&#34;UpdateExpression&#34;,&#34;messageId&#34;:&#34;unexpectedBefore&#34;,&#34;endLine&#34;:3,&#34;endColumn&#34;:20,&#34;fix&#34;:{&#34;range&#34;:[57,58],&#34;text&#34;:&#34;&#34;}},{&#34;ruleId&#34;:&#34;semi&#34;,&#34;severity&#34;:1,&#34;message&#34;:&#34;Missing semicolon.&#34;,&#34;line&#34;:3,&#34;column&#34;:20,&#34;nodeType&#34;:&#34;ReturnStatement&#34;,&#34;messageId&#34;:&#34;missingSemi&#34;,&#34;endLine&#34;:4,&#34;endColumn&#34;:1,&#34;fix&#34;:{&#34;range&#34;:[60,60],&#34;text&#34;:&#34;;&#34;}},{&#34;ruleId&#34;:&#34;no-else-return&#34;,&#34;severity&#34;:1,&#34;message&#34;:&#34;Unnecessary &#39;else&#39; after &#39;return&#39;.&#34;,&#34;line&#34;:4,&#34;column&#34;:12,&#34;nodeType&#34;:&#34;BlockStatement&#34;,&#34;messageId&#34;:&#34;unexpected&#34;,&#34;endLine&#34;:6,&#34;endColumn&#34;:6,&#34;fix&#34;:{&#34;range&#34;:[0,94],&#34;text&#34;:&#34;function addOne(i) {\n if (i != NaN) {\n return i ++\n } \n return\n \n}&#34;}},{&#34;ruleId&#34;:&#34;indent&#34;,&#34;severity&#34;:1,&#34;message&#34;:&#34;Expected indentation of 8 spaces but found 6.&#34;,&#34;line&#34;:5,&#34;column&#34;:1,&#34;nodeType&#34;:&#34;Keyword&#34;,&#34;messageId&#34;:&#34;wrongIndentation&#34;,&#34;endLine&#34;:5,&#34;endColumn&#34;:7,&#34;fix&#34;:{&#34;range&#34;:[74,80],&#34;text&#34;:&#34; &#34;}},{&#34;ruleId&#34;:&#34;consistent-return&#34;,&#34;severity&#34;:2,&#34;message&#34;:&#34;Function &#39;addOne&#39; expected a return value.&#34;,&#34;line&#34;:5,&#34;column&#34;:7,&#34;nodeType&#34;:&#34;ReturnStatement&#34;,&#34;messageId&#34;:&#34;missingReturnValue&#34;,&#34;endLine&#34;:5,&#34;endColumn&#34;:13},{&#34;ruleId&#34;:&#34;semi&#34;,&#34;severity&#34;:1,&#34;message&#34;:&#34;Missing semicolon.&#34;,&#34;line&#34;:5,&#34;column&#34;:13,&#34;nodeType&#34;:&#34;ReturnStatement&#34;,&#34;messageId&#34;:&#34;missingSemi&#34;,&#34;endLine&#34;:6,&#34;endColumn&#34;:1,&#34;fix&#34;:{&#34;range&#34;:[86,86],&#34;text&#34;:&#34;;&#34;}},{&#34;ruleId&#34;:&#34;no-extra-semi&#34;,&#34;severity&#34;:2,&#34;message&#34;:&#34;Unnecessary semicolon.&#34;,&#34;line&#34;:7,&#34;column&#34;:2,&#34;nodeType&#34;:&#34;EmptyStatement&#34;,&#34;messageId&#34;:&#34;unexpected&#34;,&#34;endLine&#34;:7,&#34;endColumn&#34;:3,&#34;fix&#34;:{&#34;range&#34;:[93,95],&#34;text&#34;:&#34;}&#34;}}],&#34;suppressedMessages&#34;:[],&#34;errorCount&#34;:5,&#34;fatalErrorCount&#34;:0,&#34;warningCount&#34;:4,&#34;fixableErrorCount&#34;:2,&#34;fixableWarningCount&#34;:4,&#34;source&#34;:&#34;function addOne(i) {\n if (i != NaN) {\n return i ++\n } else {\n return\n }\n};&#34;}],&#34;metadata&#34;:{&#34;rulesMeta&#34;:{&#34;no-else-return&#34;:{&#34;type&#34;:&#34;suggestion&#34;,&#34;docs&#34;:{&#34;description&#34;:&#34;Disallow `else` blocks after `return` statements in `if` statements&#34;,&#34;recommended&#34;:false,&#34;url&#34;:&#34;https://eslint.org/docs/rules/no-else-return&#34;},&#34;schema&#34;:[{&#34;type&#34;:&#34;object&#34;,&#34;properties&#34;:{&#34;allowElseIf&#34;:{&#34;type&#34;:&#34;boolean&#34;,&#34;default&#34;:true}},&#34;additionalProperties&#34;:false}],&#34;fixable&#34;:&#34;code&#34;,&#34;messages&#34;:{&#34;unexpected&#34;:&#34;Unnecessary &#39;else&#39; after &#39;return&#39;.&#34;}},&#34;indent&#34;:{&#34;type&#34;:&#34;layout&#34;,&#34;docs&#34;:{&#34;description&#34;:&#34;Enforce consistent indentation&#34;,&#34;recommended&#34;:false,&#34;url&#34;:&#34;https://eslint.org/docs/rules/indent&#34;},&#34;fixable&#34;:&#34;whitespace&#34;,&#34;schema&#34;:[{&#34;oneOf&#34;:[{&#34;enum&#34;:[&#34;tab&#34;]},{&#34;type&#34;:&#34;integer&#34;,&#34;minimum&#34;:0}]},{&#34;type&#34;:&#34;object&#34;,&#34;properties&#34;:{&#34;SwitchCase&#34;:{&#34;type&#34;:&#34;integer&#34;,&#34;minimum&#34;:0,&#34;default&#34;:0},&#34;VariableDeclarator&#34;:{&#34;oneOf&#34;:[{&#34;oneOf&#34;:[{&#34;type&#34;:&#34;integer&#34;,&#34;minimum&#34;:0},{&#34;enum&#34;:[&#34;first&#34;,&#34;off&#34;]}]},{&#34;type&#34;:&#34;object&#34;,&#34;properties&#34;:{&#34;var&#34;:{&#34;oneOf&#34;:[{&#34;type&#34;:&#34;integer&#34;,&#34;minimum&#34;:0},{&#34;enum&#34;:[&#34;first&#34;,&#34;off&#34;]}]},&#34;let&#34;:{&#34;oneOf&#34;:[{&#34;type&#34;:&#34;integer&#34;,&#34;minimum&#34;:0},{&#34;enum&#34;:[&#34;first&#34;,&#34;off&#34;]}]},&#34;const&#34;:{&#34;oneOf&#34;:[{&#34;type&#34;:&#34;integer&#34;,&#34;minimum&#34;:0},{&#34;enum&#34;:[&#34;first&#34;,&#34;off&#34;]}]}},&#34;additionalProperties&#34;:false}]},&#34;outerIIFEBody&#34;:{&#34;oneOf&#34;:[{&#34;type&#34;:&#34;integer&#34;,&#34;minimum&#34;:0},{&#34;enum&#34;:[&#34;off&#34;]}]},&#34;MemberExpression&#34;:{&#34;oneOf&#34;:[{&#34;type&#34;:&#34;integer&#34;,&#34;minimum&#34;:0},{&#34;enum&#34;:[&#34;off&#34;]}]},&#34;FunctionDeclaration&#34;:{&#34;type&#34;:&#34;object&#34;,&#34;properties&#34;:{&#34;parameters&#34;:{&#34;oneOf&#34;:[{&#34;type&#34;:&#34;integer&#34;,&#34;minimum&#34;:0},{&#34;enum&#34;:[&#34;first&#34;,&#34;off&#34;]}]},&#34;body&#34;:{&#34;type&#34;:&#34;integer&#34;,&#34;minimum&#34;:0}},&#34;additionalProperties&#34;:false},&#34;FunctionExpression&#34;:{&#34;type&#34;:&#34;object&#34;,&#34;properties&#34;:{&#34;parameters&#34;:{&#34;oneOf&#34;:[{&#34;type&#34;:&#34;integer&#34;,&#34;minimum&#34;:0},{&#34;enum&#34;:[&#34;first&#34;,&#34;off&#34;]}]},&#34;body&#34;:{&#34;type&#34;:&#34;integer&#34;,&#34;minimum&#34;:0}},&#34;additionalProperties&#34;:false},&#34;StaticBlock&#34;:{&#34;type&#34;:&#34;object&#34;,&#34;properties&#34;:{&#34;body&#34;:{&#34;type&#34;:&#34;integer&#34;,&#34;minimum&#34;:0}},&#34;additionalProperties&#34;:false},&#34;CallExpression&#34;:{&#34;type&#34;:&#34;object&#34;,&#34;properties&#34;:{&#34;arguments&#34;:{&#34;oneOf&#34;:[{&#34;type&#34;:&#34;integer&#34;,&#34;minimum&#34;:0},{&#34;enum&#34;:[&#34;first&#34;,&#34;off&#34;]}]}},&#34;additionalProperties&#34;:false},&#34;ArrayExpression&#34;:{&#34;oneOf&#34;:[{&#34;type&#34;:&#34;integer&#34;,&#34;minimum&#34;:0},{&#34;enum&#34;:[&#34;first&#34;,&#34;off&#34;]}]},&#34;ObjectExpression&#34;:{&#34;oneOf&#34;:[{&#34;type&#34;:&#34;integer&#34;,&#34;minimum&#34;:0},{&#34;enum&#34;:[&#34;first&#34;,&#34;off&#34;]}]},&#34;ImportDeclaration&#34;:{&#34;oneOf&#34;:[{&#34;type&#34;:&#34;integer&#34;,&#34;minimum&#34;:0},{&#34;enum&#34;:[&#34;first&#34;,&#34;off&#34;]}]},&#34;flatTernaryExpressions&#34;:{&#34;type&#34;:&#34;boolean&#34;,&#34;default&#34;:false},&#34;offsetTernaryExpressions&#34;:{&#34;type&#34;:&#34;boolean&#34;,&#34;default&#34;:false},&#34;ignoredNodes&#34;:{&#34;type&#34;:&#34;array&#34;,&#34;items&#34;:{&#34;type&#34;:&#34;string&#34;,&#34;not&#34;:{&#34;pattern&#34;:&#34;:exit$&#34;}}},&#34;ignoreComments&#34;:{&#34;type&#34;:&#34;boolean&#34;,&#34;default&#34;:false}},&#34;additionalProperties&#34;:false}],&#34;messages&#34;:{&#34;wrongIndentation&#34;:&#34;Expected indentation of but found .&#34;}},&#34;space-unary-ops&#34;:{&#34;type&#34;:&#34;layout&#34;,&#34;docs&#34;:{&#34;description&#34;:&#34;Enforce consistent spacing before or after unary operators&#34;,&#34;recommended&#34;:false,&#34;url&#34;:&#34;https://eslint.org/docs/rules/space-unary-ops&#34;},&#34;fixable&#34;:&#34;whitespace&#34;,&#34;schema&#34;:[{&#34;type&#34;:&#34;object&#34;,&#34;properties&#34;:{&#34;words&#34;:{&#34;type&#34;:&#34;boolean&#34;,&#34;default&#34;:true},&#34;nonwords&#34;:{&#34;type&#34;:&#34;boolean&#34;,&#34;default&#34;:false},&#34;overrides&#34;:{&#34;type&#34;:&#34;object&#34;,&#34;additionalProperties&#34;:{&#34;type&#34;:&#34;boolean&#34;}}},&#34;additionalProperties&#34;:false}],&#34;messages&#34;:{&#34;unexpectedBefore&#34;:&#34;Unexpected space before unary operator &#39;&#39;.&#34;,&#34;unexpectedAfter&#34;:&#34;Unexpected space after unary operator &#39;&#39;.&#34;,&#34;unexpectedAfterWord&#34;:&#34;Unexpected space after unary word operator &#39;&#39;.&#34;,&#34;wordOperator&#34;:&#34;Unary word operator &#39;&#39; must be followed by whitespace.&#34;,&#34;operator&#34;:&#34;Unary operator &#39;&#39; must be followed by whitespace.&#34;,&#34;beforeUnaryExpressions&#34;:&#34;Space is required before unary expressions &#39;&#39;.&#34;}},&#34;semi&#34;:{&#34;type&#34;:&#34;layout&#34;,&#34;docs&#34;:{&#34;description&#34;:&#34;Require or disallow semicolons instead of ASI&#34;,&#34;recommended&#34;:false,&#34;url&#34;:&#34;https://eslint.org/docs/rules/semi&#34;},&#34;fixable&#34;:&#34;code&#34;,&#34;schema&#34;:{&#34;anyOf&#34;:[{&#34;type&#34;:&#34;array&#34;,&#34;items&#34;:[{&#34;enum&#34;:[&#34;never&#34;]},{&#34;type&#34;:&#34;object&#34;,&#34;properties&#34;:{&#34;beforeStatementContinuationChars&#34;:{&#34;enum&#34;:[&#34;always&#34;,&#34;any&#34;,&#34;never&#34;]}},&#34;additionalProperties&#34;:false}],&#34;minItems&#34;:0,&#34;maxItems&#34;:2},{&#34;type&#34;:&#34;array&#34;,&#34;items&#34;:[{&#34;enum&#34;:[&#34;always&#34;]},{&#34;type&#34;:&#34;object&#34;,&#34;properties&#34;:{&#34;omitLastInOneLineBlock&#34;:{&#34;type&#34;:&#34;boolean&#34;}},&#34;additionalProperties&#34;:false}],&#34;minItems&#34;:0,&#34;maxItems&#34;:2}]},&#34;messages&#34;:{&#34;missingSemi&#34;:&#34;Missing semicolon.&#34;,&#34;extraSemi&#34;:&#34;Extra semicolon.&#34;}},&#34;consistent-return&#34;:{&#34;type&#34;:&#34;suggestion&#34;,&#34;docs&#34;:{&#34;description&#34;:&#34;Require `return` statements to either always or never specify values&#34;,&#34;recommended&#34;:false,&#34;url&#34;:&#34;https://eslint.org/docs/rules/consistent-return&#34;},&#34;schema&#34;:[{&#34;type&#34;:&#34;object&#34;,&#34;properties&#34;:{&#34;treatUndefinedAsUnspecified&#34;:{&#34;type&#34;:&#34;boolean&#34;,&#34;default&#34;:false}},&#34;additionalProperties&#34;:false}],&#34;messages&#34;:{&#34;missingReturn&#34;:&#34;Expected to return a value at the end of .&#34;,&#34;missingReturnValue&#34;:&#34; expected a return value.&#34;,&#34;unexpectedReturnValue&#34;:&#34; expected no return value.&#34;}}}}} ``` ### json Outputs JSON-serialized results. The `json` formatter is useful when you want to programmatically work with the CLI's linting results. Alternatively, you can use the [ESLint Node.js API](../../developer-guide/nodejs-api) to programmatically use ESLint. Example output: ``` [{&#34;filePath&#34;:&#34;/var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems.js&#34;,&#34;messages&#34;:[{&#34;ruleId&#34;:&#34;no-unused-vars&#34;,&#34;severity&#34;:2,&#34;message&#34;:&#34;&#39;addOne&#39; is defined but never used.&#34;,&#34;line&#34;:1,&#34;column&#34;:10,&#34;nodeType&#34;:&#34;Identifier&#34;,&#34;messageId&#34;:&#34;unusedVar&#34;,&#34;endLine&#34;:1,&#34;endColumn&#34;:16},{&#34;ruleId&#34;:&#34;use-isnan&#34;,&#34;severity&#34;:2,&#34;message&#34;:&#34;Use the isNaN function to compare with NaN.&#34;,&#34;line&#34;:2,&#34;column&#34;:9,&#34;nodeType&#34;:&#34;BinaryExpression&#34;,&#34;messageId&#34;:&#34;comparisonWithNaN&#34;,&#34;endLine&#34;:2,&#34;endColumn&#34;:17},{&#34;ruleId&#34;:&#34;space-unary-ops&#34;,&#34;severity&#34;:2,&#34;message&#34;:&#34;Unexpected space before unary operator &#39;++&#39;.&#34;,&#34;line&#34;:3,&#34;column&#34;:16,&#34;nodeType&#34;:&#34;UpdateExpression&#34;,&#34;messageId&#34;:&#34;unexpectedBefore&#34;,&#34;endLine&#34;:3,&#34;endColumn&#34;:20,&#34;fix&#34;:{&#34;range&#34;:[57,58],&#34;text&#34;:&#34;&#34;}},{&#34;ruleId&#34;:&#34;semi&#34;,&#34;severity&#34;:1,&#34;message&#34;:&#34;Missing semicolon.&#34;,&#34;line&#34;:3,&#34;column&#34;:20,&#34;nodeType&#34;:&#34;ReturnStatement&#34;,&#34;messageId&#34;:&#34;missingSemi&#34;,&#34;endLine&#34;:4,&#34;endColumn&#34;:1,&#34;fix&#34;:{&#34;range&#34;:[60,60],&#34;text&#34;:&#34;;&#34;}},{&#34;ruleId&#34;:&#34;no-else-return&#34;,&#34;severity&#34;:1,&#34;message&#34;:&#34;Unnecessary &#39;else&#39; after &#39;return&#39;.&#34;,&#34;line&#34;:4,&#34;column&#34;:12,&#34;nodeType&#34;:&#34;BlockStatement&#34;,&#34;messageId&#34;:&#34;unexpected&#34;,&#34;endLine&#34;:6,&#34;endColumn&#34;:6,&#34;fix&#34;:{&#34;range&#34;:[0,94],&#34;text&#34;:&#34;function addOne(i) {\n if (i != NaN) {\n return i ++\n } \n return\n \n}&#34;}},{&#34;ruleId&#34;:&#34;indent&#34;,&#34;severity&#34;:1,&#34;message&#34;:&#34;Expected indentation of 8 spaces but found 6.&#34;,&#34;line&#34;:5,&#34;column&#34;:1,&#34;nodeType&#34;:&#34;Keyword&#34;,&#34;messageId&#34;:&#34;wrongIndentation&#34;,&#34;endLine&#34;:5,&#34;endColumn&#34;:7,&#34;fix&#34;:{&#34;range&#34;:[74,80],&#34;text&#34;:&#34; &#34;}},{&#34;ruleId&#34;:&#34;consistent-return&#34;,&#34;severity&#34;:2,&#34;message&#34;:&#34;Function &#39;addOne&#39; expected a return value.&#34;,&#34;line&#34;:5,&#34;column&#34;:7,&#34;nodeType&#34;:&#34;ReturnStatement&#34;,&#34;messageId&#34;:&#34;missingReturnValue&#34;,&#34;endLine&#34;:5,&#34;endColumn&#34;:13},{&#34;ruleId&#34;:&#34;semi&#34;,&#34;severity&#34;:1,&#34;message&#34;:&#34;Missing semicolon.&#34;,&#34;line&#34;:5,&#34;column&#34;:13,&#34;nodeType&#34;:&#34;ReturnStatement&#34;,&#34;messageId&#34;:&#34;missingSemi&#34;,&#34;endLine&#34;:6,&#34;endColumn&#34;:1,&#34;fix&#34;:{&#34;range&#34;:[86,86],&#34;text&#34;:&#34;;&#34;}},{&#34;ruleId&#34;:&#34;no-extra-semi&#34;,&#34;severity&#34;:2,&#34;message&#34;:&#34;Unnecessary semicolon.&#34;,&#34;line&#34;:7,&#34;column&#34;:2,&#34;nodeType&#34;:&#34;EmptyStatement&#34;,&#34;messageId&#34;:&#34;unexpected&#34;,&#34;endLine&#34;:7,&#34;endColumn&#34;:3,&#34;fix&#34;:{&#34;range&#34;:[93,95],&#34;text&#34;:&#34;}&#34;}}],&#34;suppressedMessages&#34;:[],&#34;errorCount&#34;:5,&#34;fatalErrorCount&#34;:0,&#34;warningCount&#34;:4,&#34;fixableErrorCount&#34;:2,&#34;fixableWarningCount&#34;:4,&#34;source&#34;:&#34;function addOne(i) {\n if (i != NaN) {\n return i ++\n } else {\n return\n }\n};&#34;}] ``` ### junit Outputs results to format compatible with the [JUnit Jenkins plugin](https://plugins.jenkins.io/junit/). Example output: ``` &lt;?xml version=&#34;1.0&#34; encoding=&#34;utf-8&#34;?&gt; &lt;testsuites&gt; &lt;testsuite package=&#34;org.eslint&#34; time=&#34;0&#34; tests=&#34;9&#34; errors=&#34;9&#34; name=&#34;/var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems.js&#34;&gt; &lt;testcase time=&#34;0&#34; name=&#34;org.eslint.no-unused-vars&#34; classname=&#34;/var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems&#34;&gt;&lt;failure message=&#34;&amp;apos;addOne&amp;apos; is defined but never used.&#34;&gt;&lt;![CDATA[line 1, col 10, Error - &amp;apos;addOne&amp;apos; is defined but never used. (no-unused-vars)]]&gt;&lt;/failure&gt;&lt;/testcase&gt; &lt;testcase time=&#34;0&#34; name=&#34;org.eslint.use-isnan&#34; classname=&#34;/var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems&#34;&gt;&lt;failure message=&#34;Use the isNaN function to compare with NaN.&#34;&gt;&lt;![CDATA[line 2, col 9, Error - Use the isNaN function to compare with NaN. (use-isnan)]]&gt;&lt;/failure&gt;&lt;/testcase&gt; &lt;testcase time=&#34;0&#34; name=&#34;org.eslint.space-unary-ops&#34; classname=&#34;/var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems&#34;&gt;&lt;failure message=&#34;Unexpected space before unary operator &amp;apos;++&amp;apos;.&#34;&gt;&lt;![CDATA[line 3, col 16, Error - Unexpected space before unary operator &amp;apos;++&amp;apos;. (space-unary-ops)]]&gt;&lt;/failure&gt;&lt;/testcase&gt; &lt;testcase time=&#34;0&#34; name=&#34;org.eslint.semi&#34; classname=&#34;/var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems&#34;&gt;&lt;failure message=&#34;Missing semicolon.&#34;&gt;&lt;![CDATA[line 3, col 20, Warning - Missing semicolon. (semi)]]&gt;&lt;/failure&gt;&lt;/testcase&gt; &lt;testcase time=&#34;0&#34; name=&#34;org.eslint.no-else-return&#34; classname=&#34;/var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems&#34;&gt;&lt;failure message=&#34;Unnecessary &amp;apos;else&amp;apos; after &amp;apos;return&amp;apos;.&#34;&gt;&lt;![CDATA[line 4, col 12, Warning - Unnecessary &amp;apos;else&amp;apos; after &amp;apos;return&amp;apos;. (no-else-return)]]&gt;&lt;/failure&gt;&lt;/testcase&gt; &lt;testcase time=&#34;0&#34; name=&#34;org.eslint.indent&#34; classname=&#34;/var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems&#34;&gt;&lt;failure message=&#34;Expected indentation of 8 spaces but found 6.&#34;&gt;&lt;![CDATA[line 5, col 1, Warning - Expected indentation of 8 spaces but found 6. (indent)]]&gt;&lt;/failure&gt;&lt;/testcase&gt; &lt;testcase time=&#34;0&#34; name=&#34;org.eslint.consistent-return&#34; classname=&#34;/var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems&#34;&gt;&lt;failure message=&#34;Function &amp;apos;addOne&amp;apos; expected a return value.&#34;&gt;&lt;![CDATA[line 5, col 7, Error - Function &amp;apos;addOne&amp;apos; expected a return value. (consistent-return)]]&gt;&lt;/failure&gt;&lt;/testcase&gt; &lt;testcase time=&#34;0&#34; name=&#34;org.eslint.semi&#34; classname=&#34;/var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems&#34;&gt;&lt;failure message=&#34;Missing semicolon.&#34;&gt;&lt;![CDATA[line 5, col 13, Warning - Missing semicolon. (semi)]]&gt;&lt;/failure&gt;&lt;/testcase&gt; &lt;testcase time=&#34;0&#34; name=&#34;org.eslint.no-extra-semi&#34; classname=&#34;/var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems&#34;&gt;&lt;failure message=&#34;Unnecessary semicolon.&#34;&gt;&lt;![CDATA[line 7, col 2, Error - Unnecessary semicolon. (no-extra-semi)]]&gt;&lt;/failure&gt;&lt;/testcase&gt; &lt;/testsuite&gt; &lt;/testsuites&gt; ``` ### stylish Human-readable output format. This is the default formatter. Example output: ``` /var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems.js 1:10 error &#39;addOne&#39; is defined but never used no-unused-vars 2:9 error Use the isNaN function to compare with NaN use-isnan 3:16 error Unexpected space before unary operator &#39;++&#39; space-unary-ops 3:20 warning Missing semicolon semi 4:12 warning Unnecessary &#39;else&#39; after &#39;return&#39; no-else-return 5:1 warning Expected indentation of 8 spaces but found 6 indent 5:7 error Function &#39;addOne&#39; expected a return value consistent-return 5:13 warning Missing semicolon semi 7:2 error Unnecessary semicolon no-extra-semi ✖ 9 problems (5 errors, 4 warnings) 2 errors and 4 warnings potentially fixable with the `--fix` option. ``` ### tap Outputs results to the [Test Anything Protocol (TAP)](https://testanything.org/) specification format. Example output: ``` TAP version 13 1..1 not ok 1 - /var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems.js --- message: &#39;&#39;&#39;addOne&#39;&#39; is defined but never used.&#39; severity: error data: line: 1 column: 10 ruleId: no-unused-vars messages: - message: Use the isNaN function to compare with NaN. severity: error data: line: 2 column: 9 ruleId: use-isnan - message: Unexpected space before unary operator &#39;++&#39;. severity: error data: line: 3 column: 16 ruleId: space-unary-ops - message: Missing semicolon. severity: warning data: line: 3 column: 20 ruleId: semi - message: Unnecessary &#39;else&#39; after &#39;return&#39;. severity: warning data: line: 4 column: 12 ruleId: no-else-return - message: Expected indentation of 8 spaces but found 6. severity: warning data: line: 5 column: 1 ruleId: indent - message: Function &#39;addOne&#39; expected a return value. severity: error data: line: 5 column: 7 ruleId: consistent-return - message: Missing semicolon. severity: warning data: line: 5 column: 13 ruleId: semi - message: Unnecessary semicolon. severity: error data: line: 7 column: 2 ruleId: no-extra-semi ... ``` ### unix Outputs results to a format similar to many commands in UNIX-like systems. Parsable with tools such as [grep](https://www.gnu.org/software/grep/manual/grep.html), [sed](https://www.gnu.org/software/sed/manual/sed.html), and [awk](https://www.gnu.org/software/gawk/manual/gawk.html). Example output: ``` /var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems.js:1:10: &#39;addOne&#39; is defined but never used. [Error/no-unused-vars] /var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems.js:2:9: Use the isNaN function to compare with NaN. [Error/use-isnan] /var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems.js:3:16: Unexpected space before unary operator &#39;++&#39;. [Error/space-unary-ops] /var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems.js:3:20: Missing semicolon. [Warning/semi] /var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems.js:4:12: Unnecessary &#39;else&#39; after &#39;return&#39;. [Warning/no-else-return] /var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems.js:5:1: Expected indentation of 8 spaces but found 6. [Warning/indent] /var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems.js:5:7: Function &#39;addOne&#39; expected a return value. [Error/consistent-return] /var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems.js:5:13: Missing semicolon. [Warning/semi] /var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems.js:7:2: Unnecessary semicolon. [Error/no-extra-semi] 9 problems ``` ### visualstudio Outputs results to format compatible with the integrated terminal of the [Visual Studio](https://visualstudio.microsoft.com/) IDE. When using Visual Studio, you can click on the linting results in the integrated terminal to go to the issue in the source code. Example output: ``` /var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems.js(1,10): error no-unused-vars : &#39;addOne&#39; is defined but never used. /var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems.js(2,9): error use-isnan : Use the isNaN function to compare with NaN. /var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems.js(3,16): error space-unary-ops : Unexpected space before unary operator &#39;++&#39;. /var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems.js(3,20): warning semi : Missing semicolon. /var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems.js(4,12): warning no-else-return : Unnecessary &#39;else&#39; after &#39;return&#39;. /var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems.js(5,1): warning indent : Expected indentation of 8 spaces but found 6. /var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems.js(5,7): error consistent-return : Function &#39;addOne&#39; expected a return value. /var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems.js(5,13): warning semi : Missing semicolon. /var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems.js(7,2): error no-extra-semi : Unnecessary semicolon. 9 problems ```
programming_docs
eslint Plugins & Parsers Plugins & Parsers ================= You can extend ESLint with plugins in a variety of different ways. Plugins can include: * Custom rules to validate if your code meets a certain expectation, and what to do if it does not meet that expectation. * Custom configurations. * Custom environments. * Custom processors to extract JavaScript code from other kinds of files or preprocess code before linting. You can also use custom parsers to convert JavaScript code into an abstract syntax tree for ESLint to evaluate. You might want to add a custom parser if your code isn’t compatible with ESLint’s default parser, Espree. Configure Plugins ----------------- ESLint supports the use of third-party plugins. Before using a plugin, you have to install it using npm. To configure plugins inside of a configuration file, use the `plugins` key, which contains a list of plugin names. The `eslint-plugin-` prefix can be omitted from the plugin name. ``` { "plugins": [ "plugin1", "eslint-plugin-plugin2" ] } ``` And in YAML: ``` --- plugins: - plugin1 - eslint-plugin-plugin2 ``` **Notes:** 1. Plugins are resolved relative to the config file. In other words, ESLint loads the plugin as a user would obtain by running `require('eslint-plugin-pluginname')` in the config file. 2. Plugins in the base configuration (loaded by `extends` setting) are relative to the derived config file. For example, if `./.eslintrc` has `extends: ["foo"]` and the `eslint-config-foo` has `plugins: ["bar"]`, ESLint finds the `eslint-plugin-bar` from `./node_modules/` (rather than `./node_modules/eslint-config-foo/node_modules/`) or ancestor directories. Thus every plugin in the config file and base configurations is resolved uniquely. ### Naming convention #### Include a plugin The `eslint-plugin-` prefix can be omitted for both non-scoped and scoped packages. A non-scoped package: ``` { // ... "plugins": [ "jquery", // means eslint-plugin-jquery ] // ... } ``` A scoped package: ``` { // ... "plugins": [ "@jquery/jquery", // means @jquery/eslint-plugin-jquery "@foobar" // means @foobar/eslint-plugin ] // ... } ``` #### Use a plugin Rules, environments, and configurations defined in plugins must be referenced with the following convention: * `eslint-plugin-foo` → `foo/a-rule` * `@foo/eslint-plugin` → `@foo/a-config` * `@foo/eslint-plugin-bar` → `@foo/bar/a-environment` For example: ``` { // ... "plugins": [ "jquery", // eslint-plugin-jquery "@foo/foo", // @foo/eslint-plugin-foo "@bar" // @bar/eslint-plugin ], "extends": [ "plugin:@foo/foo/recommended", "plugin:@bar/recommended" ], "rules": { "jquery/a-rule": "error", "@foo/foo/some-rule": "error", "@bar/another-rule": "error" }, "env": { "jquery/jquery": true, "@foo/foo/env-foo": true, "@bar/env-bar": true, } // ... } ``` ### Specify a Processor Plugins may provide processors. Processors can extract JavaScript code from other kinds of files, then let ESLint lint the JavaScript code. Alternatively, processors can convert JavaScript code during preprocessing. To specify processors in a configuration file, use the `processor` key with the concatenated string of a plugin name and a processor name by a slash. For example, the following enables the processor `a-processor` that the plugin `a-plugin` provided: ``` { "plugins": ["a-plugin"], "processor": "a-plugin/a-processor" } ``` To specify processors for specific kinds of files, use the combination of the `overrides` key and the `processor` key. For example, the following uses the processor `a-plugin/markdown` for `*.md` files. ``` { "plugins": ["a-plugin"], "overrides": [ { "files": ["\*.md"], "processor": "a-plugin/markdown" } ] } ``` Processors may make named code blocks such as `0.js` and `1.js`. ESLint handles such a named code block as a child file of the original file. You can specify additional configurations for named code blocks in the `overrides` section of the config. For example, the following disables the `strict` rule for the named code blocks which end with `.js` in markdown files. ``` { "plugins": ["a-plugin"], "overrides": [ { "files": ["\*.md"], "processor": "a-plugin/markdown" }, { "files": ["\*\*/\*.md/\*.js"], "rules": { "strict": "off" } } ] } ``` ESLint checks the file path of named code blocks then ignores those if any `overrides` entry didn’t match the file path. Be sure to add an `overrides` entry if you want to lint named code blocks other than `*.js`. Configure a Parser ------------------ By default, ESLint uses [Espree](https://github.com/eslint/espree) as its parser. You can optionally specify that a different parser should be used in your configuration file if the parser meets the following requirements: 1. It must be a Node module loadable from the config file where the parser is used. Usually, this means you should install the parser package separately using npm. 2. It must conform to the [parser interface](developer-guide/working-with-custom-parsers). Note that even with these compatibilities, there are no guarantees that an external parser works correctly with ESLint. ESLint does not fix bugs related to incompatibilities with other parsers. To indicate the npm module to use as your parser, specify it using the `parser` option in your `.eslintrc` file. For example, the following specifies to use Esprima instead of Espree: ``` { "parser": "esprima", "rules": { "semi": "error" } } ``` The following parsers are compatible with ESLint: * [Esprima](https://www.npmjs.com/package/esprima) * [@babel/eslint-parser](https://www.npmjs.com/package/@babel/eslint-parser) - A wrapper around the [Babel](https://babeljs.io) parser that makes it compatible with ESLint. * [@typescript-eslint/parser](https://www.npmjs.com/package/@typescript-eslint/parser) - A parser that converts TypeScript into an ESTree-compatible form so it can be used in ESLint. Note that when using a custom parser, the `parserOptions` configuration property is still required for ESLint to work properly with features not in ECMAScript 5 by default. Parsers are all passed `parserOptions` and may or may not use them to determine which features to enable. eslint Configuring ESLint Configuring ESLint ================== ESLint is designed to be flexible and configurable for your use case. You can turn off every rule and run only with basic syntax validation or mix and match the bundled rules and your custom rules to fit the needs of your project. There are two primary ways to configure ESLint: 1. **Configuration Comments** - use JavaScript comments to embed configuration information directly into a file. 2. **Configuration Files** - use a JavaScript, JSON, or YAML file to specify configuration information for an entire directory and all of its subdirectories. This can be in the form of a [`.eslintrc.*`](configuration-files#configuration-file-formats) file or an `eslintConfig` field in a [`package.json`](https://docs.npmjs.com/files/package.json) file, both of which ESLint will look for and read automatically, or you can specify a configuration file on the [command line](../command-line-interface). Here are some of the options that you can configure in ESLint: * [**Environments**](language-options#specifying-environments) - which environments your script is designed to run in. Each environment brings with it a certain set of predefined global variables. * [**Globals**](language-options#specifying-globals) - the additional global variables your script accesses during execution. * [**Rules**](rules) - which rules are enabled and at what error level. * [**Plugins**](plugins) - which third-party plugins define additional rules, environments, configs, etc. for ESLint to use. All of these options give you fine-grained control over how ESLint treats your code. Table of Contents ----------------- [**Configuration Files**](configuration-files) * [Configuration File Formats](configuration-files#configuration-file-formats) * [Using Configuration Files](configuration-files#using-configuration-files) * [Adding Shared Settings](configuration-files#adding-shared-settings) * [Cascading and Hierarchy](configuration-files#cascading-and-hierarchy) * [Extending Configuration Files](configuration-files#extending-configuration-files) * [Configuration Based on Glob Patterns](configuration-files#configuration-based-on-glob-patterns) * [Personal Configuration Files](configuration-files#personal-configuration-files-deprecated) [**Language Options**](language-options) * [Specifying Environments](language-options#specifying-environments) * [Specifying Globals](language-options#specifying-globals) * [Specifying Parser Options](language-options#specifying-parser-options) [**Rules**](rules) * [Configuring Rules](rules#configuring-rules) * [Disabling Rules](rules#disabling-rules) [**Plugins**](plugins) * [Configuring Plugins](plugins#configure-plugins) * [Specifying Processors](plugins#specify-a-processor) * [Configuring Parsers](plugins#configure-a-parser) [**Ignoring Code**](ignoring-code) * [`ignorePatterns` in Config Files](ignoring-code#ignorepatterns-in-config-files) * [The `.eslintignore` File](ignoring-code#the-eslintignore-file) * [Using an Alternate File](ignoring-code#using-an-alternate-file) * [Using eslintIgnore in package.json](ignoring-code#using-eslintignore-in-packagejson) * [Ignored File Warnings](ignoring-code#ignored-file-warnings) eslint Configuration Files Configuration Files =================== You can put your ESLint project configuration in a configuration file. You can include built-in rules, how you want them enforced, plugins with custom rules, shareable configurations, which files you want rules to apply to, and more. Configuration File Formats -------------------------- ESLint supports configuration files in several formats: * **JavaScript** - use `.eslintrc.js` and export an object containing your configuration. * **JavaScript (ESM)** - use `.eslintrc.cjs` when running ESLint in JavaScript packages that specify `"type":"module"` in their `package.json`. Note that ESLint does not support ESM configuration at this time. * **YAML** - use `.eslintrc.yaml` or `.eslintrc.yml` to define the configuration structure. * **JSON** - use `.eslintrc.json` to define the configuration structure. ESLint’s JSON files also allow JavaScript-style comments. * **package.json** - create an `eslintConfig` property in your `package.json` file and define your configuration there. If there are multiple configuration files in the same directory, ESLint only uses one. The priority order is as follows: 1. `.eslintrc.js` 2. `.eslintrc.cjs` 3. `.eslintrc.yaml` 4. `.eslintrc.yml` 5. `.eslintrc.json` 6. `package.json` Using Configuration Files ------------------------- There are two ways to use configuration files. The first way to use configuration files is via `.eslintrc.*` and `package.json` files. ESLint automatically looks for them in the directory of the file to be linted, and in successive parent directories all the way up to the root directory of the filesystem (`/`), the home directory of the current user (`~/`), or when `root: true` is specified. See [Cascading and Hierarchy](#cascading-and-hierarchy) below for more details on this. Configuration files can be useful when you want different configurations for different parts of a project or when you want others to be able to use ESLint directly without needing to remember to pass in the configuration file. The second way to use configuration files is to save the file wherever you would like and pass its location to the CLI using the `--config` option, such as: ``` eslint -c myconfig.json myfiletotest.js ``` If you are using one configuration file and want ESLint to ignore any `.eslintrc.*` files, make sure to use [`--no-eslintrc`](configuration-files../command-line-interface#--no-eslintrc) along with the [`--config`](user-guide/command-line-interface#-c---config) flag. Here’s an example JSON configuration file that uses the `typescript-eslint` parser to support TypeScript syntax: ``` { "root": true, "extends": [ "eslint:recommended", "plugin:@typescript-eslint/recommended" ], "parser": "@typescript-eslint/parser", "parserOptions": { "project": ["./tsconfig.json"] }, "plugins": [ "@typescript-eslint" ], "rules": { "@typescript-eslint/strict-boolean-expressions": [ 2, { "allowString" : false, "allowNumber" : false } ] }, "ignorePatterns": ["src/\*\*/\*.test.ts", "src/frontend/generated/\*"] } ``` ### Comments in configuration files Both the JSON and YAML configuration file formats support comments (`package.json` files should not include them). You can use JavaScript-style comments for JSON files and YAML-style comments for YAML files. ESLint safely ignores comments in configuration files. This allows your configuration files to be more human-friendly. For JavaScript-style comments: ``` { "env": { "browser": true }, "rules": { // Override our default settings just for this directory "eqeqeq": "warn", "strict": "off" } } ``` For YAML-style comments: ``` env: browser: true rules: # Override default settings eqeqeq: warn strict: off ``` Adding Shared Settings ---------------------- ESLint supports adding shared settings into configuration files. Plugins use `settings` to specify the information that should be shared across all of its rules. You can add a `settings` object to the ESLint configuration file and it is supplied to every executed rule. This may be useful if you are adding custom rules and want them to have access to the same information and be easily configurable. In JSON: ``` { "settings": { "sharedData": "Hello" } } ``` And in YAML: ``` --- settings: sharedData: "Hello" ``` Cascading and Hierarchy ----------------------- When using `.eslintrc.*` and `package.json` files for configuration, you can take advantage of configuration cascading. Suppose your project has the following structure: ``` your-project ├── .eslintrc.json ├── lib │ └── source.js └─┬ tests ├── .eslintrc.json └── test.js ``` The configuration cascade works based on the location of the file being linted. If there is a `.eslintrc` file in the same directory as the file being linted, then that configuration takes precedence. ESLint then searches up the directory structure, merging any `.eslintrc` files it finds along the way until reaching either a `.eslintrc` file with `root: true` or the root directory. In the same way, if there is a `package.json` file in the root directory with an `eslintConfig` field, the configuration it describes is applied to all subdirectories beneath it. However, the configuration described by the `.eslintrc` file in the `tests/` directory overrides conflicting specifications. ``` your-project ├── package.json ├── lib │ └── source.js └─┬ tests ├── .eslintrc.json └── test.js ``` If there is a `.eslintrc` and a `package.json` file found in the same directory, `.eslintrc` takes priority and the `package.json` file is not used. By default, ESLint looks for configuration files in all parent folders up to the root directory. This can be useful if you want all of your projects to follow a certain convention, but can sometimes lead to unexpected results. To limit ESLint to a specific project, place `"root": true` inside the `.eslintrc.*` file or `eslintConfig` field of the `package.json` file or in the `.eslintrc.*` file at your project’s root level. ESLint stops looking in parent folders once it finds a configuration with `"root": true`. ``` { "root": true } ``` And in YAML: ``` --- root: true ``` For example, consider `projectA` which has `"root": true` set in the `.eslintrc` file in the `lib/` directory. In this case, while linting `main.js`, the configurations within `lib/` are used, but the `.eslintrc` file in `projectA/` is not. ``` home └── user └── projectA ├── .eslintrc.json <- Not used └── lib ├── .eslintrc.json <- { "root": true } └── main.js ``` The complete configuration hierarchy, from highest to lowest precedence, is as follows: 1. Inline configuration 1. `/*eslint-disable*/` and `/*eslint-enable*/` 2. `/*global*/` 3. `/*eslint*/` 4. `/*eslint-env*/` 2. Command line options (or CLIEngine equivalents): 1. `--global` 2. `--rule` 3. `--env` 4. `-c`, `--config` 3. Project-level configuration: 1. `.eslintrc.*` or `package.json` file in the same directory as the linted file 2. Continue searching for `.eslintrc.*` and `package.json` files in ancestor directories up to and including the root directory or until a config with `"root": true` is found. Please note that the [home directory of the current user on your preferred operating system](https://nodejs.org/api/os.html#os_os_homedir) (`~/`) is also considered a root directory in this context and searching for configuration files stops there as well. And with the [removal of support for Personal Configuration Files](configuration-filesconfiguration-files#personal-configuration-files-deprecated) from the 8.0.0 release forward, configuration files present in that directory are ignored. Extending Configuration Files ----------------------------- A configuration file, once extended, can inherit all the traits of another configuration file (including rules, plugins, and language options) and modify all the options. As a result, there are three configurations, as defined below: * Base config: the configuration that is extended. * Derived config: the configuration that extends the base configuration. * Resulting actual config: the result of merging the derived configuration into the base configuration. The `extends` property value is either: * a string that specifies a configuration (either a path to a config file, the name of a shareable config, `eslint:recommended`, or `eslint:all`) * an array of strings where each additional configuration extends the preceding configurations ESLint extends configurations recursively, so a base configuration can also have an `extends` property. Relative paths and shareable config names in an `extends` property are resolved from the location of the config file where they appear. The `eslint-config-` prefix can be omitted from the configuration name. For example, `airbnb` resolves as `eslint-config-airbnb`. The `rules` property can do any of the following to extend (or override) the set of rules: * enable additional rules * change an inherited rule’s severity without changing its options: + Base config: `"eqeqeq": ["error", "allow-null"]` + Derived config: `"eqeqeq": "warn"` + Resulting actual config: `"eqeqeq": ["warn", "allow-null"]` * override options for rules from base configurations: + Base config: `"quotes": ["error", "single", "avoid-escape"]` + Derived config: `"quotes": ["error", "single"]` + Resulting actual config: `"quotes": ["error", "single"]` * override options for rules given as object from base configurations: + Base config: `"max-lines": ["error", { "max": 200, "skipBlankLines": true, "skipComments": true }]` + Derived config: `"max-lines": ["error", { "max": 100 }]` + Resulting actual config: `"max-lines": ["error", { "max": 100 }]` where `skipBlankLines` and `skipComments` default to `false` ### Using a shareable configuration package A [sharable configuration](developer-guide/shareable-configs) is an npm package that exports a configuration object. Make sure that you have installed the package in your project root directory, so that ESLint can require it. The `extends` property value can omit the `eslint-config-` prefix of the package name. The `npm init @eslint/config` command can create a configuration so you can extend a popular style guide (for example, `eslint-config-standard`). Example of a configuration file in YAML format: ``` extends: standard rules: comma-dangle: - error - always no-empty: warn ``` ### Using `eslint:recommended` Using `"eslint:recommended"` in the `extends` property enables a subset of core rules that report common problems (these rules are identified with a checkmark (recommended) on the [rules page](rules/index)). Here’s an example of extending `eslint:recommended` and overriding some of the set configuration options: Example of a configuration file in JavaScript format: ``` module.exports = { "extends": "eslint:recommended", "rules": { // enable additional rules "indent": ["error", 4], "linebreak-style": ["error", "unix"], "quotes": ["error", "double"], "semi": ["error", "always"], // override configuration set by extending "eslint:recommended" "no-empty": "warn", "no-cond-assign": ["error", "always"], // disable rules from base configurations "for-direction": "off", } } ``` ### Using a configuration from a plugin A [plugin](developer-guide/working-with-plugins) is an npm package that can add various extensions to ESLint. A plugin can perform numerous functions, including but not limited to adding new rules and exporting [shareable configurations](developer-guide/working-with-plugins#configs-in-plugins). Make sure the package has been installed in a directory where ESLint can require it. The `plugins` [property value](configuration-files./plugins#configure-plugins) can omit the `eslint-plugin-` prefix of the package name. The `extends` property value can consist of: * `plugin:` * the package name (from which you can omit the prefix, for example, `react` is short for `eslint-plugin-react`) * `/` * the configuration name (for example, `recommended`) Example of a configuration file in JSON format: ``` { "plugins": [ "react" ], "extends": [ "eslint:recommended", "plugin:react/recommended" ], "rules": { "react/no-set-state": "off" } } ``` ### Using a configuration file The `extends` property value can be an absolute or relative path to a base [configuration file](#using-configuration-files). ESLint resolves a relative path to a base configuration file relative to the configuration file that uses it. Example of a configuration file in JSON format: ``` { "extends": [ "./node\_modules/coding-standard/eslintDefaults.js", "./node\_modules/coding-standard/.eslintrc-es6", "./node\_modules/coding-standard/.eslintrc-jsx" ], "rules": { "eqeqeq": "warn" } } ``` ### Using `"eslint:all"` The `extends` property value can be `"eslint:all"` to enable all core rules in the currently installed version of ESLint. The set of core rules can change at any minor or major version of ESLint. **Important:** This configuration is **not recommended for production use** because it changes with every minor and major version of ESLint. Use it at your own risk. You might enable all core rules as a shortcut to explore rules and options while you decide on the configuration for a project, especially if you rarely override options or disable rules. The default options for rules are not endorsements by ESLint (for example, the default option for the [`quotes`](rules/quotes) rule does not mean double quotes are better than single quotes). If your configuration extends `eslint:all`, after you upgrade to a newer major or minor version of ESLint, review the reported problems before you use the `--fix` option on the [command line](configuration-files../command-line-interface#--fix), so you know if a new fixable rule will make changes to the code. Example of a configuration file in JavaScript format: ``` module.exports = { "extends": "eslint:all", "rules": { // override default options "comma-dangle": ["error", "always"], "indent": ["error", 2], "no-cond-assign": ["error", "always"], // disable now, but enable in the future "one-var": "off", // ["error", "never"] // disable "init-declarations": "off", "no-console": "off", "no-inline-comments": "off", } } ``` Configuration Based on Glob Patterns ------------------------------------ **v4.1.0+.** Sometimes a more fine-controlled configuration is necessary, like if the configuration for files within the same directory has to be different. In this case, you can provide configurations under the `overrides` key that only apply to files that match specific glob patterns, using the same format you would pass on the command line (e.g., `app/**/*.test.js`). Glob patterns in overrides use [minimatch syntax](https://github.com/isaacs/minimatch). ### How do overrides work? It is possible to override settings based on file glob patterns in your configuration by using the `overrides` key. An example of using the `overrides` key is as follows: In your `.eslintrc.json`: ``` { "rules": { "quotes": ["error", "double"] }, "overrides": [ { "files": ["bin/\*.js", "lib/\*.js"], "excludedFiles": "\*.test.js", "rules": { "quotes": ["error", "single"] } } ] } ``` Here is how overrides work in a configuration file: * The patterns are applied against the file path relative to the directory of the config file. For example, if your config file has the path `/Users/john/workspace/any-project/.eslintrc.js` and the file you want to lint has the path `/Users/john/workspace/any-project/lib/util.js`, then the pattern provided in `.eslintrc.js` is executed against the relative path `lib/util.js`. * Glob pattern overrides have higher precedence than the regular configuration in the same config file. Multiple overrides within the same config are applied in order. That is, the last override block in a config file always has the highest precedence. * A glob specific configuration works almost the same as any other ESLint config. Override blocks can contain any configuration options that are valid in a regular config, with the exception of `root` and `ignorePatterns`. + A glob specific configuration can have an `extends` setting, but the `root` property in the extended configs is ignored. The `ignorePatterns` property in the extended configs is used only for the files the glob specific configuration matched. + Nested `overrides` settings are applied only if the glob patterns of both the parent config and the child config are matched. This is the same when the extended configs have an `overrides` setting. * Multiple glob patterns can be provided within a single override block. A file must match at least one of the supplied patterns for the configuration to apply. * Override blocks can also specify patterns to exclude from matches. If a file matches any of the excluded patterns, the configuration won’t apply. ### Relative glob patterns ``` project-root ├── app │ ├── lib │ │ ├── foo.js │ │ ├── fooSpec.js │ ├── components │ │ ├── bar.js │ │ ├── barSpec.js │ ├── .eslintrc.json ├── server │ ├── server.js │ ├── serverSpec.js ├── .eslintrc.json ``` The config in `app/.eslintrc.json` defines the glob pattern `**/*Spec.js`. This pattern is relative to the base directory of `app/.eslintrc.json`. So, this pattern would match `app/lib/fooSpec.js` and `app/components/barSpec.js` but **NOT** `server/serverSpec.js`. If you defined the same pattern in the `.eslintrc.json` file within in the `project-root` folder, it would match all three of the `*Spec` files. If a config is provided via the `--config` CLI option, the glob patterns in the config are relative to the current working directory rather than the base directory of the given config. For example, if `--config configs/.eslintrc.json` is present, the glob patterns in the config are relative to `.` rather than `./configs`. ### Specifying target files to lint If you specified directories with CLI (e.g., `eslint lib`), ESLint searches target files in the directory to lint. The target files are `*.js` or the files that match any of `overrides` entries (but exclude entries that are any of `files` end with `*`). If you specified the [`--ext`](configuration-files../command-line-interface#--ext) command line option along with directories, the target files are only the files that have specified file extensions regardless of `overrides` entries. Personal Configuration Files (deprecated) ----------------------------------------- ⚠️ **This feature has been deprecated**. This feature was removed in the 8.0.0 release. If you want to continue to use personal configuration files, please use the [`--config` CLI option](configuration-files../command-line-interface#-c---config). For more information regarding this decision, please see [RFC 28](https://github.com/eslint/rfcs/pull/28) and [RFC 32](https://github.com/eslint/rfcs/pull/32). `~/` refers to [the home directory of the current user on your preferred operating system](https://nodejs.org/api/os.html#os_os_homedir). The personal configuration file being referred to here is `~/.eslintrc.*` file, which is currently handled differently than other configuration files. ### How does ESLint find personal configuration files? If `eslint` could not find any configuration file in the project, `eslint` loads `~/.eslintrc.*` file. If `eslint` could find configuration files in the project, `eslint` ignores `~/.eslintrc.*` file even if it’s in an ancestor directory of the project directory. ### How do personal configuration files behave? `~/.eslintrc.*` files behave similarly to regular configuration files, with some exceptions: `~/.eslintrc.*` files load shareable configs and custom parsers from `~/node_modules/` – similarly to `require()` – in the user’s home directory. Please note that it doesn’t load global-installed packages. `~/.eslintrc.*` files load plugins from `$CWD/node_modules` by default in order to identify plugins uniquely. If you want to use plugins with `~/.eslintrc.*` files, plugins must be installed locally per project. Alternatively, you can use the [`--resolve-plugins-relative-to` CLI option](configuration-files../command-line-interface#--resolve-plugins-relative-to) to change the location from which ESLint loads plugins.
programming_docs
eslint Language Options Language Options ================ The JavaScript ecosystem has a variety of runtimes, versions, extensions, and frameworks. Each of these can have different supported syntax and global variables. ESLint lets you configure language options specific to the JavaScript used in your project, like custom global variables. You can also use plugins to extend ESLint to support your project’s language options. Specifying Environments ----------------------- An environment provides predefined global variables. The available environments are: * `browser` - browser global variables. * `node` - Node.js global variables and Node.js scoping. * `commonjs` - CommonJS global variables and CommonJS scoping (use this for browser-only code that uses Browserify/WebPack). * `shared-node-browser` - Globals common to both Node.js and Browser. * `es6` - enable all ECMAScript 6 features except for modules (this automatically sets the `ecmaVersion` parser option to 6). * `es2016` - adds all ECMAScript 2016 globals and automatically sets the `ecmaVersion` parser option to 7. * `es2017` - adds all ECMAScript 2017 globals and automatically sets the `ecmaVersion` parser option to 8. * `es2018` - adds all ECMAScript 2018 globals and automatically sets the `ecmaVersion` parser option to 9. * `es2019` - adds all ECMAScript 2019 globals and automatically sets the `ecmaVersion` parser option to 10. * `es2020` - adds all ECMAScript 2020 globals and automatically sets the `ecmaVersion` parser option to 11. * `es2021` - adds all ECMAScript 2021 globals and automatically sets the `ecmaVersion` parser option to 12. * `es2022` - adds all ECMAScript 2022 globals and automatically sets the `ecmaVersion` parser option to 13. * `worker` - web workers global variables. * `amd` - defines `require()` and `define()` as global variables as per the [amd](https://github.com/amdjs/amdjs-api/wiki/AMD) spec. * `mocha` - adds all of the Mocha testing global variables. * `jasmine` - adds all of the Jasmine testing global variables for version 1.3 and 2.0. * `jest` - Jest global variables. * `phantomjs` - PhantomJS global variables. * `protractor` - Protractor global variables. * `qunit` - QUnit global variables. * `jquery` - jQuery global variables. * `prototypejs` - Prototype.js global variables. * `shelljs` - ShellJS global variables. * `meteor` - Meteor global variables. * `mongo` - MongoDB global variables. * `applescript` - AppleScript global variables. * `nashorn` - Java 8 Nashorn global variables. * `serviceworker` - Service Worker global variables. * `atomtest` - Atom test helper globals. * `embertest` - Ember test helper globals. * `webextensions` - WebExtensions globals. * `greasemonkey` - GreaseMonkey globals. These environments are not mutually exclusive, so you can define more than one at a time. Environments can be specified inside of a file, in configuration files or using the `--env` [command line](language-options../command-line-interface) flag. ### Using configuration comments To specify environments with a comment inside of a JavaScript file, use the following format: ``` /\* eslint-env node, mocha \*/ ``` This enables Node.js and Mocha environments. ### Using configuration files To specify environments in a configuration file, use the `env` key. Specify which environments you want to enable by setting each to `true`. For example, the following enables the browser and Node.js environments: ``` { "env": { "browser": true, "node": true } } ``` Or in a `package.json` file ``` { "name": "mypackage", "version": "0.0.1", "eslintConfig": { "env": { "browser": true, "node": true } } } ``` And in YAML: ``` --- env: browser: true node: true ``` ### Using a plugin If you want to use an environment from a plugin, be sure to specify the plugin name in the `plugins` array and then use the unprefixed plugin name, followed by a slash, followed by the environment name. For example: ``` { "plugins": ["example"], "env": { "example/custom": true } } ``` Or in a `package.json` file ``` { "name": "mypackage", "version": "0.0.1", "eslintConfig": { "plugins": ["example"], "env": { "example/custom": true } } } ``` Specifying Globals ------------------ Some of ESLint’s core rules rely on knowledge of the global variables available to your code at runtime. Since these can vary greatly between different environments as well as be modified at runtime, ESLint makes no assumptions about what global variables exist in your execution environment. If you would like to use rules that require knowledge of what global variables are available, you can define global variables in your configuration file or by using configuration comments in your source code. ### Using configuration comments To specify globals using a comment inside of your JavaScript file, use the following format: ``` /\* global var1, var2 \*/ ``` This defines two global variables, `var1` and `var2`. If you want to optionally specify that these global variables can be written to (rather than only being read), then you can set each with a `"writable"` flag: ``` /\* global var1:writable, var2:writable \*/ ``` ### Using configuration files To configure global variables inside of a configuration file, set the `globals` configuration property to an object containing keys named for each of the global variables you want to use. For each global variable key, set the corresponding value equal to `"writable"` to allow the variable to be overwritten or `"readonly"` to disallow overwriting. For example: ``` { "globals": { "var1": "writable", "var2": "readonly" } } ``` And in YAML: ``` --- globals: var1: writable var2: readonly ``` These examples allow `var1` to be overwritten in your code, but disallow it for `var2`. Globals can be disabled by setting their value to `"off"`. For example, in an environment where most ES2015 globals are available but `Promise` is unavailable, you might use this config: ``` { "env": { "es6": true }, "globals": { "Promise": "off" } } ``` For historical reasons, the boolean value `false` and the string value `"readable"` are equivalent to `"readonly"`. Similarly, the boolean value `true` and the string value `"writeable"` are equivalent to `"writable"`. However, the use of these older values is deprecated. Specifying Parser Options ------------------------- ESLint allows you to specify the JavaScript language options you want to support. By default, ESLint expects ECMAScript 5 syntax. You can override that setting to enable support for other ECMAScript versions and JSX using parser options. Please note that supporting JSX syntax is not the same as supporting React. React applies specific semantics to JSX syntax that ESLint doesn’t recognize. We recommend using [eslint-plugin-react](https://github.com/yannickcr/eslint-plugin-react) if you are using React. By the same token, supporting ES6 syntax is not the same as supporting new ES6 globals (e.g., new types such as `Set`). For ES6 syntax, use `{ "parserOptions": { "ecmaVersion": 6 } }`; for new ES6 global variables, use `{ "env": { "es6": true } }`. Setting `{ "env": { "es6": true } }` enables ES6 syntax automatically, but `{ "parserOptions": { "ecmaVersion": 6 } }` does not enable ES6 globals automatically. Parser options are set in your `.eslintrc.*` file with the `parserOptions` property. The available options are: * `ecmaVersion` - set to 3, 5 (default), 6, 7, 8, 9, 10, 11, 12, 13, or 14 to specify the version of ECMAScript syntax you want to use. You can also set it to 2015 (same as 6), 2016 (same as 7), 2017 (same as 8), 2018 (same as 9), 2019 (same as 10), 2020 (same as 11), 2021 (same as 12), 2022 (same as 13), or 2023 (same as 14) to use the year-based naming. You can also set `"latest"` to use the most recently supported version. * `sourceType` - set to `"script"` (default) or `"module"` if your code is in ECMAScript modules. * `allowReserved` - allow the use of reserved words as identifiers (if `ecmaVersion` is 3). * `ecmaFeatures` - an object indicating which additional language features you’d like to use: + `globalReturn` - allow `return` statements in the global scope + `impliedStrict` - enable global [strict mode](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode) (if `ecmaVersion` is 5 or greater) + `jsx` - enable [JSX](https://facebook.github.io/jsx/) Here’s an example `.eslintrc.json` file: ``` { "parserOptions": { "ecmaVersion": "latest", "sourceType": "module", "ecmaFeatures": { "jsx": true } }, "rules": { "semi": "error" } } ``` Setting parser options helps ESLint determine what is a parsing error. All language options are `false` by default. eslint Rules Rules ===== Rules are the core building block of ESLint. A rule validates if your code meets a certain expectation, and what to do if it does not meet that expectation. Rules can also contain additional configuration options specific to that rule. ESLint comes with a large number of [built-in rules](rules/index) and you can add more rules through plugins. You can modify which rules your project uses with either configuration comments or configuration files. Rule Severities --------------- To change a rule’s severity, set the rule ID equal to one of these values: * `"off"` or `0` - turn the rule off * `"warn"` or `1` - turn the rule on as a warning (doesn’t affect exit code) * `"error"` or `2` - turn the rule on as an error (exit code is 1 when triggered) ### Using configuration comments To configure rules inside of a file using configuration comments, use a comment in the following format: ``` /\* eslint eqeqeq: "off", curly: "error" \*/ ``` In this example, [`eqeqeq`](rules/eqeqeq) is turned off and [`curly`](rules/curly) is turned on as an error. You can also use the numeric equivalent for the rule severity: ``` /\* eslint eqeqeq: 0, curly: 2 \*/ ``` This example is the same as the last example, only it uses the numeric codes instead of the string values. The `eqeqeq` rule is off and the `curly` rule is set to be an error. If a rule has additional options, you can specify them using array literal syntax, such as: ``` /\* eslint quotes: ["error", "double"], curly: 2 \*/ ``` This comment specifies the “double” option for the [`quotes`](rules/quotes) rule. The first item in the array is always the rule severity (number or string). #### Configuration Comment Descriptions Configuration comments can include descriptions to explain why the comment is necessary. The description must occur after the configuration and is separated from the configuration by two or more consecutive `-` characters. For example: ``` /\* eslint eqeqeq: "off", curly: "error" -- Here's a description about why this configuration is necessary. \*/ ``` ``` /\* eslint eqeqeq: "off", curly: "error" -------- Here's a description about why this configuration is necessary. \*/ ``` ``` /\* eslint eqeqeq: "off", curly: "error" \* -------- \* This will not work due to the line above starting with a '\*' character. \*/ ``` ### Using configuration files To configure rules inside of a configuration file, use the `rules` key along with an error level and any options you want to use. For example: ``` { "rules": { "eqeqeq": "off", "curly": "error", "quotes": ["error", "double"] } } ``` And in YAML: ``` --- rules: eqeqeq: off curly: error quotes: - error - double ``` Rules from Plugins ------------------ To configure a rule that is defined within a plugin, prefix the rule ID with the plugin name and `/`. In a configuration file, for example: ``` { "plugins": [ "plugin1" ], "rules": { "eqeqeq": "off", "curly": "error", "quotes": ["error", "double"], "plugin1/rule1": "error" } } ``` And in YAML: ``` --- plugins: - plugin1 rules: eqeqeq: 0 curly: error quotes: - error - "double" plugin1/rule1: error ``` In these configuration files, the rule `plugin1/rule1` comes from the plugin named `plugin1`, which is contained in an npm package named `eslint-plugin-plugin1`. You can also use this format with configuration comments, such as: ``` /\* eslint "plugin1/rule1": "error" \*/ ``` **Note:** When specifying rules from plugins, make sure to omit `eslint-plugin-`. ESLint uses only the unprefixed name internally to locate rules. Disabling Rules --------------- ### Using configuration comments To disable rule warnings in a part of a file, use block comments in the following format: ``` /\* eslint-disable \*/ alert('foo'); /\* eslint-enable \*/ ``` You can also disable or enable warnings for specific rules: ``` /\* eslint-disable no-alert, no-console \*/ alert('foo'); console.log('bar'); /\* eslint-enable no-alert, no-console \*/ ``` **Note:** `/* eslint-enable */` without any specific rules listed causes all disabled rules to be re-enabled. To disable rule warnings in an entire file, put a `/* eslint-disable */` block comment at the top of the file: ``` /\* eslint-disable \*/ alert('foo'); ``` You can also disable or enable specific rules for an entire file: ``` /\* eslint-disable no-alert \*/ alert('foo'); ``` To ensure that a rule is never applied (regardless of any future enable/disable lines): ``` /\* eslint no-alert: "off" \*/ alert('foo'); ``` To disable all rules on a specific line, use a line or block comment in one of the following formats: ``` alert('foo'); // eslint-disable-line // eslint-disable-next-line alert('foo'); /\* eslint-disable-next-line \*/ alert('foo'); alert('foo'); /\* eslint-disable-line \*/ ``` To disable a specific rule on a specific line: ``` alert('foo'); // eslint-disable-line no-alert // eslint-disable-next-line no-alert alert('foo'); alert('foo'); /\* eslint-disable-line no-alert \*/ /\* eslint-disable-next-line no-alert \*/ alert('foo'); ``` To disable multiple rules on a specific line: ``` alert('foo'); // eslint-disable-line no-alert, quotes, semi // eslint-disable-next-line no-alert, quotes, semi alert('foo'); alert('foo'); /\* eslint-disable-line no-alert, quotes, semi \*/ /\* eslint-disable-next-line no-alert, quotes, semi \*/ alert('foo'); /\* eslint-disable-next-line no-alert, quotes, semi \*/ alert('foo'); ``` All of the above methods also work for plugin rules. For example, to disable `eslint-plugin-example`’s `rule-name` rule, combine the plugin’s name (`example`) and the rule’s name (`rule-name`) into `example/rule-name`: ``` foo(); // eslint-disable-line example/rule-name foo(); /\* eslint-disable-line example/rule-name \*/ ``` **Note:** Comments that disable warnings for a portion of a file tell ESLint not to report rule violations for the disabled code. ESLint still parses the entire file, however, so disabled code still needs to be syntactically valid JavaScript. #### Comment descriptions Configuration comments can include descriptions to explain why disabling or re-enabling the rule is necessary. The description must come after the configuration and needs to be separated from the configuration by two or more consecutive `-` characters. For example: ``` // eslint-disable-next-line no-console -- Here's a description about why this configuration is necessary. console.log('hello'); /\* eslint-disable-next-line no-console -- \* Here's a very long description about why this configuration is necessary \* along with some additional information \*\*/ console.log('hello'); ``` ### Using configuration files To disable rules inside of a configuration file for a group of files, use the `overrides` key along with a `files` key. For example: ``` { "rules": {...}, "overrides": [ { "files": ["\*-test.js","\*.spec.js"], "rules": { "no-unused-expressions": "off" } } ] } ``` ### Disabling Inline Comments To disable all inline config comments, use the `noInlineConfig` setting in your configuration file. For example: ``` { "rules": {...}, "noInlineConfig": true } ``` You can also use the [–no-inline-config](rules../command-line-interface#--no-inline-config) CLI option to disable rule comments, in addition to other in-line configuration. #### Report unused `eslint-disable` comments To report unused `eslint-disable` comments, use the `reportUnusedDisableDirectives` setting. For example: ``` { "rules": {...}, "reportUnusedDisableDirectives": true } ``` This setting is similar to [–report-unused-disable-directives](rules../command-line-interface#--report-unused-disable-directives) CLI option, but doesn’t fail linting (reports as `"warn"` severity). eslint Configuration Files (New) Configuration Files (New) ========================= You can put your ESLint project configuration in a configuration file. You can include built-in rules, how you want them enforced, plugins with custom rules, shareable configurations, which files you want rules to apply to, and more. Configuration File ------------------ The ESLint configuration file is named `eslint.config.js`. It should be placed in the root directory of your project and export an array of [configuration objects](#configuration-objects). Here’s an example: ``` export default [ { rules: { semi: "error", "prefer-const": "error" } } ] ``` In this example, the configuration array contains just one configuration object. The configuration object enables two rules: `semi` and `prefer-const`. These rules are applied to all of the files ESLint processes using this config file. Configuration Objects --------------------- Each configuration object contains all of the information ESLint needs to execute on a set of files. Each configuration object is made up of these properties: * `files` - An array of glob patterns indicating the files that the configuration object should apply to. If not specified, the configuration object applies to all files. * `ignores` - An array of glob patterns indicating the files that the configuration object should not apply to. If not specified, the configuration object applies to all files matched by `files`. * `languageOptions` - An object containing settings related to how JavaScript is configured for linting. + `ecmaVersion` - The version of ECMAScript to support. May be any year (i.e., `2022`) or version (i.e., `5`). Set to `"latest"` for the most recent supported version. (default: `"latest"`) + `sourceType` - The type of JavaScript source code. Possible values are `"script"` for traditional script files, `"module"` for ECMAScript modules (ESM), and `"commonjs"` for CommonJS files. (default: `"module"` for `.js` and `.mjs` files; `"commonjs"` for `.cjs` files) + `globals` - An object specifying additional objects that should be added to the global scope during linting. + `parser` - Either an object containing a `parse()` method or a string indicating the name of a parser inside of a plugin (i.e., `"pluginName/parserName"`). (default: `"@/espree"`) + `parserOptions` - An object specifying additional options that are passed directly to the `parser()` method on the parser. The available options are parser-dependent. * `linterOptions` - An object containing settings related to the linting process. + `noInlineConfig` - A Boolean value indicating if inline configuration is allowed. + `reportUnusedDisableDirectives` - A Boolean value indicating if unused disable directives should be tracked and reported. * `processor` - Either an object containing `preprocess()` and `postprocess()` methods or a string indicating the name of a processor inside of a plugin (i.e., `"pluginName/processorName"`). * `plugins` - An object containing a name-value mapping of plugin names to plugin objects. When `files` is specified, these plugins are only available to the matching files. * `rules` - An object containing the configured rules. When `files` or `ignores` are specified, these rule configurations are only available to the matching files. * `settings` - An object containing name-value pairs of information that should be available to all rules. ### Specifying `files` and `ignores` You can use a combination of `files` and `ignores` to determine which files should apply the configuration object and which should not. By default, ESLint matches `**/*.js`, `**/*.cjs`, and `**/*.mjs`. Because config objects that don’t specify `files` or `ignores` apply to all files that have been matched by any other configuration object, those config objects apply to any JavaScript files passed to ESLint by default. For example: ``` export default [ { rules: { semi: "error" } } ]; ``` With this configuration, the `semi` rule is enabled for all files that match the default files in ESLint. So if you pass `example.js` to ESLint, the `semi` rule is applied. If you pass a non-JavaScript file, like `example.txt`, the `semi` rule is not applied because there are no other configuration objects that match that filename. (ESLint outputs an error message letting you know that the file was ignored due to missing configuration.) #### Excluding files with `ignores` You can limit which files a configuration object applies to by specifying a combination of `files` and `ignores` patterns. For example, you may want certain rules to apply only to files in your `src` directory: ``` export default [ { files: ["src/\*\*/\*.js"], rules: { semi: "error" } } ]; ``` Here, only the JavaScript files in the `src` directory have the `semi` rule applied. If you run ESLint on files in another directory, this configuration object is skipped. By adding `ignores`, you can also remove some of the files in `src` from this configuration object: ``` export default [ { files: ["src/\*\*/\*.js"], ignores: ["\*\*/\*.config.js"], rules: { semi: "error" } } ]; ``` This configuration object matches all JavaScript files in the `src` directory except those that end with `.config.js`. You can also use negation patterns in `ignores` to exclude files from the ignore patterns, such as: ``` export default [ { files: ["src/\*\*/\*.js"], ignores: ["\*\*/\*.config.js", "!\*\*/eslint.config.js"], rules: { semi: "error" } } ]; ``` Here, the configuration object excludes files ending with `.config.js` except for `eslint.config.js`. That file still has `semi` applied. If `ignores` is used without `files` and any other setting, then the configuration object applies to all files except the ones specified in `ignores`, for example: ``` export default [ { ignores: ["\*\*/\*.config.js"], rules: { semi: "error" } } ]; ``` This configuration object applies to all files except those ending with `.config.js`. Effectively, this is like having `files` set to `**/*`. In general, it’s a good idea to always include `files` if you are specifying `ignores`. #### Globally ignoring files with `ignores` If `ignores` is used without any other keys in the configuration object, then the patterns act as global ignores. Here’s an example: ``` export default [ { ignores: [".config/\*"] } ]; ``` This configuration specifies that all of the files in the `.config` directory should be ignored. This pattern is added after the default patterns, which are `["**/node_modules/**", ".git/**"]`. #### Cascading configuration objects When more than one configuration object matches a given filename, the configuration objects are merged with later objects overriding previous objects when there is a conflict. For example: ``` export default [ { files: ["\*\*/\*.js"], languageOptions: { globals: { MY\_CUSTOM\_GLOBAL: "readonly" } } }, { files: ["tests/\*\*/\*.js"], languageOptions: { globals: { it: "readonly", describe: "readonly" } } } ]; ``` Using this configuration, all JavaScript files define a custom global object defined called `MY_CUSTOM_GLOBAL` while those JavaScript files in the `tests` directory have `it` and `describe` defined as global objects in addition to `MY_CUSTOM_GLOBAL`. For any JavaScript file in the tests directory, both configuration objects are applied, so `languageOptions.globals` are merged to create a final result. ### Configuring linter options Options specific to the linting process can be configured using the `linterOptions` object. These effect how linting proceeds and does not affect how the source code of the file is interpreted. #### Disabling inline configuration Inline configuration is implemented using an `/*eslint*/` comment, such as `/*eslint semi: error*/`. You can disallow inline configuration by setting `noInlineConfig` to `true`. When enabled, all inline configuration is ignored. Here’s an example: ``` export default [ { files: ["\*\*/\*.js"], linterOptions: { noInlineConfig: true } } ]; ``` #### Reporting unused disable directives Disable directives such as `/*eslint-disable*/` and `/*eslint-disable-next-line*/` are used to disable ESLint rules around certain portions of code. As code changes, it’s possible for these directives to no longer be needed because the code has changed in such a way that the rule is no longer triggered. You can enable reporting of these unused disable directives by setting the `reportUnusedDisableDirectives` option to `true`, as in this example: ``` export default [ { files: ["\*\*/\*.js"], linterOptions: { reportUnusedDisableDirectives: true } } ]; ``` By default, unused disable directives are reported as warnings. You can change this setting using the `--report-unused-disable-directives` command line option. ### Configuring language options Options specific to how ESLint evaluates your JavaScript code can be configured using the `languageOptions` object. #### Configuring the JavaScript version To configure the version of JavaScript (ECMAScript) that ESLint uses to evaluate your JavaScript, use the `ecmaVersion` property. This property determines which global variables and syntax are valid in your code and can be set to the version number (such as `6`), the year number (such as `2022`), or `"latest"` (for the most recent version that ESLint supports). By default, `ecmaVersion` is set to `"latest"` and it’s recommended to keep this default unless you need to ensure that your JavaScript code is evaluated as an older version. For example, some older runtimes might only allow ECMAScript 5, in which case you can configure ESLint like this: ``` export default [ { files: ["\*\*/\*.js"], languageOptions: { ecmaVersion: 5 } } ]; ``` #### Configuring the JavaScript source type ESLint can evaluate your code in one of three ways: 1. ECMAScript module (ESM) - Your code has a module scope and is run in strict mode. 2. CommonJS - Your code has a top-level function scope and runs in non-strict mode. 3. Script - Your code has a shared global scope and runs in non-strict mode. You can specify which of these modes your code is intended to run in by specifying the `sourceType` property. This property can be set to `"module"`, `"commonjs"`, or `"script"`. By default, `sourceType` is set to `"module"` for `.js` and `.mjs` files and is set to `"commonjs"` for `.cjs` files. Here’s an example: ``` export default [ { files: ["\*\*/\*.js"], languageOptions: { sourceType: "script" } } ]; ``` #### Configuring a custom parser and its options In many cases, you can use the default parser that ESLint ships with for parsing your JavaScript code. You can optionally override the default parser by using the `parser` property. The `parser` property can be either a string in the format `"pluginName/parserName"` (indicating to retrieve the parser from a plugin) or an object containing either a `parse()` method or a `parseForESLint()` method. For example, you can use the [`@babel/eslint-parser`](https://www.npmjs.com/package/@babel/eslint-parser) package to allow ESLint to parse experimental syntax: ``` import babelParser from "@babel/eslint-parser"; export default [ { files: ["\*\*/\*.js", "\*\*/\*.mjs"], languageOptions: { parser: babelParser } } ]; ``` This configuration ensures that the Babel parser, rather than the default Espree parser, is used to parse all files ending with `.js` and `.mjs`. You can also pass options directly to the custom parser by using the `parserOptions` property. This property is an object whose name-value pairs are specific to the parser that you are using. For the Babel parser, you might pass in options like this: ``` import babelParser from "@babel/eslint-parser"; export default [ { files: ["\*\*/\*.js", "\*\*/\*.mjs"], languageOptions: { parser: babelParser, parserOptions: { requireConfigFile: false, babelOptions: { babelrc: false, configFile: false, // your babel options presets: ["@babel/preset-env"], } } } } ]; ``` #### Configuring global variables To configure global variables inside of a configuration object, set the `globals` configuration property to an object containing keys named for each of the global variables you want to use. For each global variable key, set the corresponding value equal to `"writable"` to allow the variable to be overwritten or `"readonly"` to disallow overwriting. For example: ``` export default [ { files: ["\*\*/\*.js"], languageOptions: { globals: { var1: "writable", var2: "readonly" } } } ]; ``` These examples allow `var1` to be overwritten in your code, but disallow it for `var2`. Globals can be disabled with the string `"off"`. For example, in an environment where most ES2015 globals are available but `Promise` is unavailable, you might use this config: ``` export default [ { languageOptions: { globals: { Promise: "off" } } } ]; ``` For historical reasons, the boolean value `false` and the string value `"readable"` are equivalent to `"readonly"`. Similarly, the boolean value `true` and the string value `"writeable"` are equivalent to `"writable"`. However, the use of older values is deprecated. ### Using plugins in your configuration Plugins are used to share rules, processors, configurations, parsers, and more across ESLint projects. #### Using plugin rules You can use specific rules included in a plugin. To do this, specify the plugin in a configuration object using the `plugins` key. The value for the `plugin` key is an object where the name of the plugin is the property name and the value is the plugin object itself. Here’s an example: ``` import jsdoc from "eslint-plugin-jsdoc"; export default [ { files: ["\*\*/\*.js"], plugins: { jsdoc: jsdoc }, rules: { "jsdoc/require-description": "error", "jsdoc/check-values": "error" } } ]; ``` In this configuration, the JSDoc plugin is defined to have the name `jsdoc`. The prefix `jsdoc/` in each rule name indicates that the rule is coming from the plugin with that name rather than from ESLint itself. Because the name of the plugin and the plugin object are both `jsdoc`, you can also shorten the configuration to this: ``` import jsdoc from "eslint-plugin-jsdoc"; export default [ { files: ["\*\*/\*.js"], plugins: { jsdoc }, rules: { "jsdoc/require-description": "error", "jsdoc/check-values": "error" } } ]; ``` While this is the most common convention, you don’t need to use the same name that the plugin prescribes. You can specify any prefix that you’d like, such as: ``` import jsdoc from "eslint-plugin-jsdoc"; export default [ { files: ["\*\*/\*.js"], plugins: { jsd: jsdoc }, rules: { "jsd/require-description": "error", "jsd/check-values": "error" } } ]; ``` This configuration object uses `jsd` as the prefix plugin instead of `jsdoc`. #### Using configurations included in plugins You can use a configuration included in a plugin by adding that configuration directly to the `eslint.config.js` configurations array. Often, you do this for a plugin’s recommended configuration. Here’s an example: ``` import jsdoc from "eslint-plugin-jsdoc"; export default [ // configuration included in plugin jsdoc.configs.recommended, // other configuration objects... { files: ["\*\*/\*.js"], plugins: { jsdoc: jsdoc }, rules: { "jsdoc/require-description": "warn", } } ]; ``` ### Using processors Processors allow ESLint to transform text into pieces of code that ESLint can lint. You can specify the processor to use for a given file type by defining a `processor` property that contains either the processor name in the format `"pluginName/processorName"` to reference a processor in a plugin or an object containing both a `preprocess()` and a `postprocess()` method. For example, to extract JavaScript code blocks from a Markdown file, you might add this to your configuration: ``` import markdown from "eslint-plugin-markdown"; export default [ { files: ["\*\*/\*.md"], plugins: { markdown }, processor: "markdown/markdown", settings: { sharedData: "Hello" } } ]; ``` This configuration object specifies that there is a processor called `"markdown"` contained in the plugin named `"markdown"`. The configuration applies the processor to all files ending with `.md`. Processors may make named code blocks that function as filenames in configuration objects, such as `0.js` and `1.js`. ESLint handles such a named code block as a child of the original file. You can specify additional configuration objects for named code blocks. For example, the following disables the `strict` rule for the named code blocks which end with `.js` in markdown files. ``` import markdown from "eslint-plugin-markdown"; export default [ { files: ["\*\*/\*.md"], plugins: { markdown }, processor: "markdown/markdown", settings: { sharedData: "Hello" } }, // applies only to code blocks { files: ["\*\*/\*.md/\*.js"], rules: { strict: "off" } } ]; ``` ### Configuring rules You can configure any number of rules in a configuration object by add a `rules` property containing an object with your rule configurations. The names in this object are the names of the rules and the values are the configurations for each of those rules. Here’s an example: ``` export default [ { rules: { semi: "error" } } ]; ``` This configuration object specifies that the [`semi`](rules/semi) rule should be enabled with a severity of `"error"`. You can also provide options to a rule by specifying an array where the first item is the severity and each item after that is an option for the rule. For example, you can switch the `semi` rule to disallow semicolons by passing `"never"` as an option: ``` export default [ { rules: { semi: ["error", "never"] } } ]; ``` Each rule specifies its own options and can be any valid JSON data type. Please check the documentation for the rule you want to configure for more information about its available options. #### Rule severities There are three possible severities you can specify for a rule * `"error"` (or `2`) - the reported problem should be treated as an error. When using the ESLint CLI, errors cause the CLI to exit with a nonzero code. * `"warn"` (or `1`) - the reported problem should be treated as a warning. When using the ESLint CLI, warnings are reported but do not change the exit code. If only warnings are reported, the exit code is 0. * `"off"` (or `0`) - the rule should be turned off completely. #### Rule configuration cascade When more than one configuration object specifies the same rule, the rule configuration is merged with the later object taking precedence over any previous objects. For example: ``` export default [ { rules: { semi: ["error", "never"] } }, { rules: { semi: ["warn", "always"] } } ]; ``` Using this configuration, the final rule configuration for `semi` is `["warn", "always"]` because it appears last in the array. The array indicates that the configuration is for the severity and any options. You can change just the severity by defining only a string or number, as in this example: ``` export default [ { rules: { semi: ["error", "never"] } }, { rules: { semi: "warn" } } ]; ``` Here, the second configuration object only overrides the severity, so the final configuration for `semi` is `["warn", "never"]`. ### Configuring shared settings ESLint supports adding shared settings into configuration files. When you add a `settings` object to a configuration object, it is supplied to every rule. By convention, plugins namespace the settings they are interested in to avoid collisions with others. Plugins can use `settings` to specify the information that should be shared across all of their rules. This may be useful if you are adding custom rules and want them to have access to the same information. Here’s an example: ``` export default [ { settings: { sharedData: "Hello" } } ]; ``` ### Using predefined configurations ESLint has two predefined configurations: * `eslint:recommended` - enables the rules that ESLint recommends everyone use to avoid potential errors * `eslint:all` - enables all of the rules shipped with ESLint To include these predefined configurations, you can insert the string values into the returned array and then make any modifications to other properties in subsequent configuration objects: ``` export default [ "eslint:recommended", { rules: { semi: ["warn", "always"] } } ]; ``` Here, the `eslint:recommended` predefined configuration is applied first and then another configuration object adds the desired configuration for `semi`. Configuration File Resolution ----------------------------- When ESLint is run on the command line, it first checks the current working directory for `eslint.config.js`. If the file is not found, it looks to the next parent directory for the file. This search continues until either the file is found or the root directory is reached. You can prevent this search for `eslint.config.js` by setting the `ESLINT_USE_FLAT_CONFIG` environment variable to `true` and using the `-c` or `--config` option on the command line to specify an alternate configuration file, such as: ``` ESLINT\_USE\_FLAT\_CONFIG=true npx eslint -c some-other-file.js **/*.js ``` In this case, ESLint does not search for `eslint.config.js` and instead uses `some-other-file.js`.
programming_docs
eslint Ignoring Code Ignoring Code ============= You can configure ESLint to ignore certain files and directories while linting by specifying one or more glob patterns. You can ignore files in the following ways: * Add `ignorePatterns` to a configuration file. * Create a dedicated file that contains the ignore patterns (`.eslintignore` by default). `ignorePatterns` in Config Files --------------------------------- You can tell ESLint to ignore specific files and directories using `ignorePatterns` in your config files. `ignorePatterns` patterns follow the same rules as `.eslintignore`. Please see the [`.eslintignore` file documentation](ignoring-code./ignoring-code#the-eslintignore-file) to learn more. ``` { "ignorePatterns": ["temp.js", "\*\*/vendor/\*.js"], "rules": { //... } } ``` * Glob patterns in `ignorePatterns` are relative to the directory that the config file is placed in. * You cannot write `ignorePatterns` property under `overrides` property. * Patterns defined in `.eslintignore` take precedence over the `ignorePatterns` property of config files. If a glob pattern starts with `/`, the pattern is relative to the base directory of the config file. For example, `/foo.js` in `lib/.eslintrc.json` matches to `lib/foo.js` but not `lib/subdir/foo.js`. If a config is provided via the `--config` CLI option, the ignore patterns that start with `/` in the config are relative to the current working directory rather than the base directory of the given config. For example, if `--config configs/.eslintrc.json` is present, the ignore patterns in the config are relative to `.` rather than `./configs`. The `.eslintignore` File ------------------------ You can tell ESLint to ignore specific files and directories by creating a `.eslintignore` file in your project’s root directory. The `.eslintignore` file is a plain text file where each line is a glob pattern indicating which paths should be omitted from linting. For example, the following omits all JavaScript files: ``` **/*.js ``` When ESLint is run, it looks in the current working directory to find a `.eslintignore` file before determining which files to lint. If this file is found, then those preferences are applied when traversing directories. Only one `.eslintignore` file can be used at a time, so `.eslintignore` files other than the one in the current working directory are not used. Globs are matched using [node-ignore](https://github.com/kaelzhang/node-ignore), so a number of features are available: * Lines beginning with `#` are treated as comments and do not affect the ignore patterns. * Paths are relative to the current working directory. This is also true of paths passed in via the `--ignore-pattern` [command](ignoring-code../command-line-interface#--ignore-pattern). * Lines preceded by `!` are negated patterns that re-include a pattern that was ignored by an earlier pattern. * Ignore patterns behave according to the `.gitignore` [specification](https://git-scm.com/docs/gitignore). Of particular note is that like `.gitignore` files, all paths used as patterns for both `.eslintignore` and `--ignore-pattern` must use forward slashes as their path separators. ``` # Valid /root/src/*.js # Invalid \root\src\*.js ``` Please see [`.gitignore`](https://git-scm.com/docs/gitignore)’s specification for further examples of valid syntax. In addition to any patterns in the `.eslintignore` file, ESLint always follows a couple of implicit ignore rules even if the `--no-ignore` flag is passed. The implicit rules are as follows: * `node_modules/` is ignored. * dot-files (except for `.eslintrc.*`) as well as dot-folders and their contents are ignored. There are also some exceptions to these rules: * If the path to lint is a glob pattern or directory path and contains a dot-folder, all dot-files and dot-folders are linted. This includes dot-files and dot-folders that are buried deeper in the directory structure. For example, `eslint .config/` would lint all dot-folders and dot-files in the `.config` directory, including immediate children as well as children that are deeper in the directory structure. * If the path to lint is a specific file path and the `--no-ignore` flag has been passed, ESLint would lint the file regardless of the implicit ignore rules. For example, `eslint .config/my-config-file.js --no-ignore` would cause `my-config-file.js` to be linted. It should be noted that the same command without the `--no-ignore` line would not lint the `my-config-file.js` file. * Allowlist and denylist rules specified via `--ignore-pattern` or `.eslintignore` are prioritized above implicit ignore rules. For example, in this scenario, `.build/test.js` is the desired file to allowlist. Because all dot-folders and their children are ignored by default, `.build` must first be allowlisted so that eslint becomes aware of its children. Then, `.build/test.js` must be explicitly allowlisted, while the rest of the content is denylisted. This is done with the following `.eslintignore` file: ``` # Allowlist 'test.js' in the '.build' folder # But do not allow anything else in the '.build' folder to be linted !.build .build/* !.build/test.js ``` The following `--ignore-pattern` is also equivalent: ``` eslint --ignore-pattern '!.build' --ignore-pattern '.build/\*' --ignore-pattern '!.build/test.js' parent-folder/ ``` Using an Alternate File ----------------------- If you’d prefer to use a different file than the `.eslintignore` in the current working directory, you can specify it on the command line using the `--ignore-path` option. For example, you can use `.jshintignore` file because it has the same format: ``` eslint --ignore-path .jshintignore file.js ``` You can also use your `.gitignore` file: ``` eslint --ignore-path .gitignore file.js ``` Any file that follows the standard ignore file format can be used. Keep in mind that specifying `--ignore-path` means that the existing `.eslintignore` file is not used. Note that globbing rules in `.eslintignore` follow those of `.gitignore`. Using eslintIgnore in package.json ---------------------------------- If an `.eslintignore` file is not found and an alternate file is not specified, ESLint looks in `package.json` for the `eslintIgnore` key to check for files to ignore. ``` { "name": "mypackage", "version": "0.0.1", "eslintConfig": { "env": { "browser": true, "node": true } }, "eslintIgnore": ["hello.js", "world.js"] } ``` Ignored File Warnings --------------------- When you pass directories to ESLint, files and directories are silently ignored. If you pass a specific file to ESLint, then ESLint creates a warning that the file was skipped. For example, suppose you have an `.eslintignore` file that looks like this: ``` foo.js ``` And then you run: ``` eslint foo.js ``` You’ll see this warning: ``` foo.js 0:0 warning File ignored because of a matching ignore pattern. Use "--no-ignore" to override. ✖ 1 problem (0 errors, 1 warning) ``` This message occurs because ESLint is unsure if you wanted to actually lint the file or not. As the message indicates, you can use `--no-ignore` to omit using the ignore rules. Consider another scenario where you want to run ESLint on a specific dot-file or dot-folder, but have forgotten to specifically allow those files in your `.eslintignore` file. You would run something like this: ``` eslint .config/foo.js ``` You would see this warning: ``` .config/foo.js 0:0 warning File ignored by default. Use a negated ignore pattern (like "--ignore-pattern '!<relative/path/to/filename>'") to override ✖ 1 problem (0 errors, 1 warning) ``` This message occurs because, normally, this file would be ignored by ESLint’s implicit ignore rules (as mentioned above). A negated ignore rule in your `.eslintignore` file would override the implicit rule and reinclude this file for linting. Additionally, in this case, `--no-ignore` could be used to lint the file as well. eslint Rules Rules ===== Rules are the core building block of ESLint. A rule validates if your code meets a certain expectation, and what to do if it does not meet that expectation. Rules can also contain additional configuration options specific to that rule. ESLint comes with a large number of [built-in rules](index) and you can add more rules through plugins. You can modify which rules your project uses with either configuration comments or configuration files. Rule Severities --------------- To change a rule’s severity, set the rule ID equal to one of these values: * `"off"` or `0` - turn the rule off * `"warn"` or `1` - turn the rule on as a warning (doesn’t affect exit code) * `"error"` or `2` - turn the rule on as an error (exit code is 1 when triggered) ### Using configuration comments To configure rules inside of a file using configuration comments, use a comment in the following format: ``` /\* eslint eqeqeq: "off", curly: "error" \*/ ``` In this example, [`eqeqeq`](eqeqeq) is turned off and [`curly`](curly) is turned on as an error. You can also use the numeric equivalent for the rule severity: ``` /\* eslint eqeqeq: 0, curly: 2 \*/ ``` This example is the same as the last example, only it uses the numeric codes instead of the string values. The `eqeqeq` rule is off and the `curly` rule is set to be an error. If a rule has additional options, you can specify them using array literal syntax, such as: ``` /\* eslint quotes: ["error", "double"], curly: 2 \*/ ``` This comment specifies the “double” option for the [`quotes`](quotes) rule. The first item in the array is always the rule severity (number or string). #### Configuration Comment Descriptions Configuration comments can include descriptions to explain why the comment is necessary. The description must occur after the configuration and is separated from the configuration by two or more consecutive `-` characters. For example: ``` /\* eslint eqeqeq: "off", curly: "error" -- Here's a description about why this configuration is necessary. \*/ ``` ``` /\* eslint eqeqeq: "off", curly: "error" -------- Here's a description about why this configuration is necessary. \*/ ``` ``` /\* eslint eqeqeq: "off", curly: "error" \* -------- \* This will not work due to the line above starting with a '\*' character. \*/ ``` ### Using configuration files To configure rules inside of a configuration file, use the `rules` key along with an error level and any options you want to use. For example: ``` { "rules": { "eqeqeq": "off", "curly": "error", "quotes": ["error", "double"] } } ``` And in YAML: ``` --- rules: eqeqeq: off curly: error quotes: - error - double ``` Rules from Plugins ------------------ To configure a rule that is defined within a plugin, prefix the rule ID with the plugin name and `/`. In a configuration file, for example: ``` { "plugins": [ "plugin1" ], "rules": { "eqeqeq": "off", "curly": "error", "quotes": ["error", "double"], "plugin1/rule1": "error" } } ``` And in YAML: ``` --- plugins: - plugin1 rules: eqeqeq: 0 curly: error quotes: - error - "double" plugin1/rule1: error ``` In these configuration files, the rule `plugin1/rule1` comes from the plugin named `plugin1`, which is contained in an npm package named `eslint-plugin-plugin1`. You can also use this format with configuration comments, such as: ``` /\* eslint "plugin1/rule1": "error" \*/ ``` **Note:** When specifying rules from plugins, make sure to omit `eslint-plugin-`. ESLint uses only the unprefixed name internally to locate rules. Disabling Rules --------------- ### Using configuration comments To disable rule warnings in a part of a file, use block comments in the following format: ``` /\* eslint-disable \*/ alert('foo'); /\* eslint-enable \*/ ``` You can also disable or enable warnings for specific rules: ``` /\* eslint-disable no-alert, no-console \*/ alert('foo'); console.log('bar'); /\* eslint-enable no-alert, no-console \*/ ``` **Note:** `/* eslint-enable */` without any specific rules listed causes all disabled rules to be re-enabled. To disable rule warnings in an entire file, put a `/* eslint-disable */` block comment at the top of the file: ``` /\* eslint-disable \*/ alert('foo'); ``` You can also disable or enable specific rules for an entire file: ``` /\* eslint-disable no-alert \*/ alert('foo'); ``` To ensure that a rule is never applied (regardless of any future enable/disable lines): ``` /\* eslint no-alert: "off" \*/ alert('foo'); ``` To disable all rules on a specific line, use a line or block comment in one of the following formats: ``` alert('foo'); // eslint-disable-line // eslint-disable-next-line alert('foo'); /\* eslint-disable-next-line \*/ alert('foo'); alert('foo'); /\* eslint-disable-line \*/ ``` To disable a specific rule on a specific line: ``` alert('foo'); // eslint-disable-line no-alert // eslint-disable-next-line no-alert alert('foo'); alert('foo'); /\* eslint-disable-line no-alert \*/ /\* eslint-disable-next-line no-alert \*/ alert('foo'); ``` To disable multiple rules on a specific line: ``` alert('foo'); // eslint-disable-line no-alert, quotes, semi // eslint-disable-next-line no-alert, quotes, semi alert('foo'); alert('foo'); /\* eslint-disable-line no-alert, quotes, semi \*/ /\* eslint-disable-next-line no-alert, quotes, semi \*/ alert('foo'); /\* eslint-disable-next-line no-alert, quotes, semi \*/ alert('foo'); ``` All of the above methods also work for plugin rules. For example, to disable `eslint-plugin-example`’s `rule-name` rule, combine the plugin’s name (`example`) and the rule’s name (`rule-name`) into `example/rule-name`: ``` foo(); // eslint-disable-line example/rule-name foo(); /\* eslint-disable-line example/rule-name \*/ ``` **Note:** Comments that disable warnings for a portion of a file tell ESLint not to report rule violations for the disabled code. ESLint still parses the entire file, however, so disabled code still needs to be syntactically valid JavaScript. #### Comment descriptions Configuration comments can include descriptions to explain why disabling or re-enabling the rule is necessary. The description must come after the configuration and needs to be separated from the configuration by two or more consecutive `-` characters. For example: ``` // eslint-disable-next-line no-console -- Here's a description about why this configuration is necessary. console.log('hello'); /\* eslint-disable-next-line no-console -- \* Here's a very long description about why this configuration is necessary \* along with some additional information \*\*/ console.log('hello'); ``` ### Using configuration files To disable rules inside of a configuration file for a group of files, use the `overrides` key along with a `files` key. For example: ``` { "rules": {...}, "overrides": [ { "files": ["\*-test.js","\*.spec.js"], "rules": { "no-unused-expressions": "off" } } ] } ``` ### Disabling Inline Comments To disable all inline config comments, use the `noInlineConfig` setting in your configuration file. For example: ``` { "rules": {...}, "noInlineConfig": true } ``` You can also use the [–no-inline-config](../rules../command-line-interface#--no-inline-config) CLI option to disable rule comments, in addition to other in-line configuration. #### Report unused `eslint-disable` comments To report unused `eslint-disable` comments, use the `reportUnusedDisableDirectives` setting. For example: ``` { "rules": {...}, "reportUnusedDisableDirectives": true } ``` This setting is similar to [–report-unused-disable-directives](../rules../command-line-interface#--report-unused-disable-directives) CLI option, but doesn’t fail linting (reports as `"warn"` severity). eslint no-unexpected-multiline no-unexpected-multiline ======================= Disallow confusing multiline expressions ✅ Recommended The `"extends": "eslint:recommended"` property in a [configuration file](no-unexpected-multiline../user-guide/configuring/configuration-files#extending-configuration-files) enables this rule Semicolons are usually optional in JavaScript, because of automatic semicolon insertion (ASI). You can require or disallow semicolons with the [semi](no-unexpected-multiline./semi) rule. The rules for ASI are relatively straightforward: As once described by Isaac Schlueter, a newline character always ends a statement, just like a semicolon, **except** where one of the following is true: * The statement has an unclosed paren, array literal, or object literal or ends in some other way that is not a valid way to end a statement. (For instance, ending with `.` or `,`.) * The line is `--` or `++` (in which case it will decrement/increment the next token.) * It is a `for()`, `while()`, `do`, `if()`, or `else`, and there is no `{` * The next line starts with `[`, `(`, `+`, `*`, `/`, `-`, `,`, `.`, or some other binary operator that can only be found between two tokens in a single expression. In the exceptions where a newline does **not** end a statement, a typing mistake to omit a semicolon causes two unrelated consecutive lines to be interpreted as one expression. Especially for a coding style without semicolons, readers might overlook the mistake. Although syntactically correct, the code might throw exceptions when it is executed. Rule Details ------------ This rule disallows confusing multiline expressions where a newline looks like it is ending a statement, but is not. Examples of **incorrect** code for this rule: ``` /\*eslint no-unexpected-multiline: "error"\*/ var foo = bar (1 || 2).baz(); var hello = 'world' [1, 2, 3].forEach(addNumber); let x = function() {} `hello` let x = function() {} x `hello` let x = foo /regex/g.test(bar) ``` Examples of **correct** code for this rule: ``` /\*eslint no-unexpected-multiline: "error"\*/ var foo = bar; (1 || 2).baz(); var foo = bar ;(1 || 2).baz() var hello = 'world'; [1, 2, 3].forEach(addNumber); var hello = 'world' void [1, 2, 3].forEach(addNumber); let x = function() {}; `hello` let tag = function() {} tag `hello` ``` When Not To Use It ------------------ You can turn this rule off if you are confident that you will not accidentally introduce code like this. Note that the patterns considered problems are **not** flagged by the [semi](no-unexpected-multilinesemi) rule. Related Rules ------------- * <func-call-spacing> * <semi> * <space-unary-ops> Version ------- This rule was introduced in ESLint v0.24.0. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/no-unexpected-multiline.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/no-unexpected-multiline.js) eslint no-dupe-args no-dupe-args ============ Disallow duplicate arguments in `function` definitions ✅ Recommended The `"extends": "eslint:recommended"` property in a [configuration file](no-dupe-args../user-guide/configuring/configuration-files#extending-configuration-files) enables this rule If more than one parameter has the same name in a function definition, the last occurrence “shadows” the preceding occurrences. A duplicated name might be a typing error. Rule Details ------------ This rule disallows duplicate parameter names in function declarations or expressions. It does not apply to arrow functions or class methods, because the parser reports the error. If ESLint parses code in strict mode, the parser (instead of this rule) reports the error. Examples of **incorrect** code for this rule: ``` /\*eslint no-dupe-args: "error"\*/ function foo(a, b, a) { console.log("value of the second a:", a); } var bar = function (a, b, a) { console.log("value of the second a:", a); }; ``` Examples of **correct** code for this rule: ``` /\*eslint no-dupe-args: "error"\*/ function foo(a, b, c) { console.log(a, b, c); } var bar = function (a, b, c) { console.log(a, b, c); }; ``` Version ------- This rule was introduced in ESLint v0.16.0. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/no-dupe-args.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/no-dupe-args.js)
programming_docs
eslint no-alert no-alert ======== Disallow the use of `alert`, `confirm`, and `prompt` JavaScript’s `alert`, `confirm`, and `prompt` functions are widely considered to be obtrusive as UI elements and should be replaced by a more appropriate custom UI implementation. Furthermore, `alert` is often used while debugging code, which should be removed before deployment to production. ``` alert("here!"); ``` Rule Details ------------ This rule is aimed at catching debugging code that should be removed and popup UI elements that should be replaced with less obtrusive, custom UIs. As such, it will warn when it encounters `alert`, `prompt`, and `confirm` function calls which are not shadowed. Examples of **incorrect** code for this rule: ``` /\*eslint no-alert: "error"\*/ alert("here!"); confirm("Are you sure?"); prompt("What's your name?", "John Doe"); ``` Examples of **correct** code for this rule: ``` /\*eslint no-alert: "error"\*/ customAlert("Something happened!"); customConfirm("Are you sure?"); customPrompt("Who are you?"); function foo() { var alert = myCustomLib.customAlert; alert(); } ``` Related Rules ------------- * <no-console> * <no-debugger> Version ------- This rule was introduced in ESLint v0.0.5. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/no-alert.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/no-alert.js) eslint no-nonoctal-decimal-escape no-nonoctal-decimal-escape ========================== Disallow `\8` and `\9` escape sequences in string literals ✅ Recommended The `"extends": "eslint:recommended"` property in a [configuration file](no-nonoctal-decimal-escape../user-guide/configuring/configuration-files#extending-configuration-files) enables this rule 💡 hasSuggestions Some problems reported by this rule are manually fixable by editor [suggestions](no-nonoctal-decimal-escape../developer-guide/working-with-rules#providing-suggestions) Although not being specified in the language until ECMAScript 2021, `\8` and `\9` escape sequences in string literals were allowed in most JavaScript engines, and treated as “useless” escapes: ``` "\8" === "8"; // true "\9" === "9"; // true ``` Since ECMAScript 2021, these escape sequences are specified as [non-octal decimal escape sequences](https://tc39.es/ecma262/#prod-annexB-NonOctalDecimalEscapeSequence), retaining the same behavior. Nevertheless, the ECMAScript specification treats `\8` and `\9` in string literals as a legacy feature. This syntax is optional if the ECMAScript host is not a web browser. Browsers still have to support it, but only in non-strict mode. Regardless of your targeted environment, these escape sequences shouldn’t be used when writing new code. Rule Details ------------ This rule disallows `\8` and `\9` escape sequences in string literals. Examples of **incorrect** code for this rule: ``` /\*eslint no-nonoctal-decimal-escape: "error"\*/ "\8"; "\9"; var foo = "w\8less"; var bar = "December 1\9"; var baz = "Don't use \8 and \9 escapes."; var quux = "\0\8"; ``` Examples of **correct** code for this rule: ``` /\*eslint no-nonoctal-decimal-escape: "error"\*/ "8"; "9"; var foo = "w8less"; var bar = "December 19"; var baz = "Don't use \\8 and \\9 escapes."; var quux = "\0\u0038"; ``` Related Rules ------------- * <no-octal-escape> Version ------- This rule was introduced in ESLint v7.14.0. Further Reading --------------- [ECMAScript® 2023 Language Specification](https://tc39.es/ecma262/#prod-annexB-NonOctalDecimalEscapeSequence) Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/no-nonoctal-decimal-escape.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/no-nonoctal-decimal-escape.js) eslint getter-return getter-return ============= Enforce `return` statements in getters ✅ Recommended The `"extends": "eslint:recommended"` property in a [configuration file](getter-return../user-guide/configuring/configuration-files#extending-configuration-files) enables this rule The get syntax binds an object property to a function that will be called when that property is looked up. It was first introduced in ECMAScript 5: ``` var p = { get name(){ return "nicholas"; } }; Object.defineProperty(p, "age", { get: function (){ return 17; } }); ``` Note that every `getter` is expected to return a value. Rule Details ------------ This rule enforces that a return statement is present in property getters. Examples of **incorrect** code for this rule: ``` /\*eslint getter-return: "error"\*/ p = { get name(){ // no returns. } }; Object.defineProperty(p, "age", { get: function (){ // no returns. } }); class P{ get name(){ // no returns. } } ``` Examples of **correct** code for this rule: ``` /\*eslint getter-return: "error"\*/ p = { get name(){ return "nicholas"; } }; Object.defineProperty(p, "age", { get: function (){ return 18; } }); class P{ get name(){ return "nicholas"; } } ``` Options ------- This rule has an object option: * `"allowImplicit": false` (default) disallows implicitly returning `undefined` with a `return` statement. Examples of **correct** code for the `{ "allowImplicit": true }` option: ``` /\*eslint getter-return: ["error", { allowImplicit: true }]\*/ p = { get name(){ return; // return undefined implicitly. } }; ``` When Not To Use It ------------------ If your project will not be using ES5 property getters you do not need this rule. Version ------- This rule was introduced in ESLint v4.2.0. Further Reading --------------- [getter - JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get) [Read Understanding ECMAScript 6 | Leanpub](https://leanpub.com/understandinges6/read/#leanpub-auto-accessor-properties) Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/getter-return.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/getter-return.js) eslint id-match id-match ======== Require identifiers to match a specified regular expression > “There are only two hard things in Computer Science: cache invalidation and naming things.” — Phil Karlton > > Naming things consistently in a project is an often underestimated aspect of code creation. When done correctly, it can save your team hours of unnecessary head scratching and misdirections. This rule allows you to precisely define and enforce the variables and function names on your team should use. No more limiting yourself to camelCase, snake\_case, PascalCase or oHungarianNotation. Id-match has all your needs covered! Rule Details ------------ This rule requires identifiers in assignments and `function` definitions to match a specified regular expression. Options ------- This rule has a string option for the specified regular expression. For example, to enforce a camelcase naming convention: ``` { "id-match": ["error", "^[a-z]+([A-Z][a-z]+)\*$"] } ``` Examples of **incorrect** code for this rule with the `"^[a-z]+([A-Z][a-z]+)*$"` option: ``` /\*eslint id-match: ["error", "^[a-z]+([A-Z][a-z]+)\*$"]\*/ var my_favorite_color = "#112C85"; var _myFavoriteColor = "#112C85"; var myFavoriteColor_ = "#112C85"; var MY\_FAVORITE\_COLOR = "#112C85"; function do\_something() { // ... } obj.do\_something = function() { // ... }; class My\_Class {} class myClass { do\_something() {} } class myClass { #do\_something() {} } ``` Examples of **correct** code for this rule with the `"^[a-z]+([A-Z][a-z]+)*$"` option: ``` /\*eslint id-match: ["error", "^[a-z]+([A-Z][a-z]+)\*$"]\*/ var myFavoriteColor = "#112C85"; var foo = bar.baz_boom; var foo = { qux: bar.baz_boom }; do\_something(); var obj = { my\_pref: 1 }; class myClass {} class myClass { doSomething() {} } class myClass { #doSomething() {} } ``` This rule has an object option: * `"properties": false` (default) does not check object properties * `"properties": true` requires object literal properties and member expression assignment properties to match the specified regular expression * `"classFields": false` (default) does not class field names * `"classFields": true` requires class field names to match the specified regular expression * `"onlyDeclarations": false` (default) requires all variable names to match the specified regular expression * `"onlyDeclarations": true` requires only `var`, `function`, and `class` declarations to match the specified regular expression * `"ignoreDestructuring": false` (default) enforces `id-match` for destructured identifiers * `"ignoreDestructuring": true` does not check destructured identifiers ### properties Examples of **incorrect** code for this rule with the `"^[a-z]+([A-Z][a-z]+)*$", { "properties": true }` options: ``` /\*eslint id-match: ["error", "^[a-z]+([A-Z][a-z]+)\*$", { "properties": true }]\*/ var obj = { my\_pref: 1 }; ``` ### classFields Examples of **incorrect** code for this rule with the `"^[a-z]+([A-Z][a-z]+)*$", { "classFields": true }` options: ``` /\*eslint id-match: ["error", "^[a-z]+([A-Z][a-z]+)\*$", { "properties": true }]\*/ class myClass { my_pref = 1; } class myClass { #my_pref = 1; } ``` ### onlyDeclarations Examples of **correct** code for this rule with the `"^[a-z]+([A-Z][a-z]+)*$", { "onlyDeclarations": true }` options: ``` /\*eslint id-match: [2, "^[a-z]+([A-Z][a-z]+)\*$", { "onlyDeclarations": true }]\*/ do\_something(__dirname); ``` ### ignoreDestructuring: false Examples of **incorrect** code for this rule with the default `"^[^_]+$", { "ignoreDestructuring": false }` option: ``` /\*eslint id-match: [2, "^[^\_]+$", { "ignoreDestructuring": false }]\*/ var { category_id } = query; var { category_id = 1 } = query; var { category\_id: category_id } = query; var { category\_id: category_alias } = query; var { category\_id: categoryId, ...other_props } = query; ``` ### ignoreDestructuring: true Examples of **incorrect** code for this rule with the `"^[^_]+$", { "ignoreDestructuring": true }` option: ``` /\*eslint id-match: [2, "^[^\_]+$", { "ignoreDestructuring": true }]\*/ var { category\_id: category_alias } = query; var { category_id, ...other_props } = query; ``` Examples of **correct** code for this rule with the `"^[^_]+$", { "ignoreDestructuring": true }` option: ``` /\*eslint id-match: [2, "^[^\_]+$", { "ignoreDestructuring": true }]\*/ var { category_id } = query; var { category_id = 1 } = query; var { category\_id: category_id } = query; ``` When Not To Use It ------------------ If you don’t want to enforce any particular naming convention for all identifiers, or your naming convention is too complex to be enforced by configuring this rule, then you should not enable this rule. Version ------- This rule was introduced in ESLint v1.0.0. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/id-match.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/id-match.js) eslint sort-keys sort-keys ========= Require object keys to be sorted When declaring multiple properties, some developers prefer to sort property names alphabetically to more easily find and/or diff necessary properties at a later time. Others feel that it adds complexity and becomes burden to maintain. Rule Details ------------ This rule checks all property definitions of object expressions and verifies that all variables are sorted alphabetically. Examples of **incorrect** code for this rule: ``` /\*eslint sort-keys: "error"\*/ /\*eslint-env es6\*/ let obj = {a: 1, c: 3, b: 2}; let obj = {a: 1, "c": 3, b: 2}; // Case-sensitive by default. let obj = {a: 1, b: 2, C: 3}; // Non-natural order by default. let obj = {1: a, 2: c, 10: b}; // This rule checks computed properties which have a simple name as well. // Simple names are names which are expressed by an Identifier node or a Literal node. const S = Symbol("s") let obj = {a: 1, ["c"]: 3, b: 2}; let obj = {a: 1, [S]: 3, b: 2}; ``` Examples of **correct** code for this rule: ``` /\*eslint sort-keys: "error"\*/ /\*eslint-env es6\*/ let obj = {a: 1, b: 2, c: 3}; let obj = {a: 1, "b": 2, c: 3}; // Case-sensitive by default. let obj = {C: 3, a: 1, b: 2}; // Non-natural order by default. let obj = {1: a, 10: b, 2: c}; // This rule checks computed properties which have a simple name as well. let obj = {a: 1, ["b"]: 2, c: 3}; let obj = {a: 1, [b]: 2, c: 3}; // This rule ignores computed properties which have a non-simple name. let obj = {a: 1, [c + d]: 3, b: 2}; let obj = {a: 1, ["c" + "d"]: 3, b: 2}; let obj = {a: 1, [`${c}`]: 3, b: 2}; let obj = {a: 1, [tag`c`]: 3, b: 2}; // This rule does not report unsorted properties that are separated by a spread property. let obj = {b: 1, ...c, a: 2}; ``` Options ------- ``` { "sort-keys": ["error", "asc", {"caseSensitive": true, "natural": false, "minKeys": 2}] } ``` The 1st option is `"asc"` or `"desc"`. * `"asc"` (default) - enforce properties to be in ascending order. * `"desc"` - enforce properties to be in descending order. The 2nd option is an object which has 3 properties. * `caseSensitive` - if `true`, enforce properties to be in case-sensitive order. Default is `true`. * `minKeys` - Specifies the minimum number of keys that an object should have in order for the object’s unsorted keys to produce an error. Default is `2`, which means by default all objects with unsorted keys will result in lint errors. * `natural` - if `true`, enforce properties to be in natural order. Default is `false`. Natural Order compares strings containing combination of letters and numbers in the way a human being would sort. It basically sorts numerically, instead of sorting alphabetically. So the number 10 comes after the number 3 in Natural Sorting. * `allowLineSeparatedGroups` - if `true`, the rule allows to group object keys through line breaks. In other words, a blank line after a property will reset the sorting of keys. Default is `false`. Example for a list: With `natural` as true, the ordering would be 1 3 6 8 10 With `natural` as false, the ordering would be 1 10 3 6 8 ### desc Examples of **incorrect** code for the `"desc"` option: ``` /\*eslint sort-keys: ["error", "desc"]\*/ /\*eslint-env es6\*/ let obj = {b: 2, c: 3, a: 1}; let obj = {"b": 2, c: 3, a: 1}; // Case-sensitive by default. let obj = {C: 1, b: 3, a: 2}; // Non-natural order by default. let obj = {10: b, 2: c, 1: a}; ``` Examples of **correct** code for the `"desc"` option: ``` /\*eslint sort-keys: ["error", "desc"]\*/ /\*eslint-env es6\*/ let obj = {c: 3, b: 2, a: 1}; let obj = {c: 3, "b": 2, a: 1}; // Case-sensitive by default. let obj = {b: 3, a: 2, C: 1}; // Non-natural order by default. let obj = {2: c, 10: b, 1: a}; ``` ### insensitive Examples of **incorrect** code for the `{caseSensitive: false}` option: ``` /\*eslint sort-keys: ["error", "asc", {caseSensitive: false}]\*/ /\*eslint-env es6\*/ let obj = {a: 1, c: 3, C: 4, b: 2}; let obj = {a: 1, C: 3, c: 4, b: 2}; ``` Examples of **correct** code for the `{caseSensitive: false}` option: ``` /\*eslint sort-keys: ["error", "asc", {caseSensitive: false}]\*/ /\*eslint-env es6\*/ let obj = {a: 1, b: 2, c: 3, C: 4}; let obj = {a: 1, b: 2, C: 3, c: 4}; ``` ### natural Examples of **incorrect** code for the `{natural: true}` option: ``` /\*eslint sort-keys: ["error", "asc", {natural: true}]\*/ /\*eslint-env es6\*/ let obj = {1: a, 10: c, 2: b}; ``` Examples of **correct** code for the `{natural: true}` option: ``` /\*eslint sort-keys: ["error", "asc", {natural: true}]\*/ /\*eslint-env es6\*/ let obj = {1: a, 2: b, 10: c}; ``` ### minKeys Examples of **incorrect** code for the `{minKeys: 4}` option: ``` /\*eslint sort-keys: ["error", "asc", {minKeys: 4}]\*/ /\*eslint-env es6\*/ // 4 keys let obj = { b: 2, a: 1, // not sorted correctly (should be 1st key) c: 3, d: 4, }; // 5 keys let obj = { 2: 'a', 1: 'b', // not sorted correctly (should be 1st key) 3: 'c', 4: 'd', 5: 'e', }; ``` Examples of **correct** code for the `{minKeys: 4}` option: ``` /\*eslint sort-keys: ["error", "asc", {minKeys: 4}]\*/ /\*eslint-env es6\*/ // 3 keys let obj = { b: 2, a: 1, c: 3, }; // 2 keys let obj = { 2: 'b', 1: 'a', }; ``` ### allowLineSeparatedGroups Examples of **incorrect** code for the `{allowLineSeparatedGroups: true}` option: ``` /\*eslint sort-keys: ["error", "asc", {allowLineSeparatedGroups: true}]\*/ /\*eslint-env es6\*/ let obj1 = { b: 1, c () { }, a: 3 } let obj2 = { b: 1, c: 2, z () { }, y: 3 } let obj3 = { b: 1, c: 2, z () { }, // comment y: 3, } let obj4 = { b: 1 // comment before comma , a: 2 }; ``` Examples of **correct** code for the `{allowLineSeparatedGroups: true}` option: ``` /\*eslint sort-keys: ["error", "asc", {allowLineSeparatedGroups: true}]\*/ /\*eslint-env es6\*/ let obj = { e: 1, f: 2, g: 3, a: 4, b: 5, c: 6 } let obj = { b: 1, // comment a: 4, c: 5, } let obj = { c: 1, d: 2, b () { }, e: 3, } let obj = { c: 1, d: 2, // comment // comment b() { }, e: 4 } let obj = { b, [foo + bar]: 1, a } let obj = { b: 1 // comment before comma , a: 2 }; var obj = { b: 1, a: 2, ...z, c: 3 } ``` When Not To Use It ------------------ If you don’t want to notify about properties’ order, then it’s safe to disable this rule. Compatibility ------------- * **JSCS:** [validateOrderInObjectKeys](https://jscs-dev.github.io/rule/validateOrderInObjectKeys) Related Rules ------------- * <sort-imports> * <sort-vars> Version ------- This rule was introduced in ESLint v3.3.0. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/sort-keys.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/sort-keys.js) eslint operator-linebreak operator-linebreak ================== Enforce consistent linebreak style for operators 🔧 Fixable Some problems reported by this rule are automatically fixable by the `--fix` [command line](operator-linebreak../user-guide/command-line-interface#--fix) option When a statement is too long to fit on a single line, line breaks are generally inserted next to the operators separating expressions. The first style coming to mind would be to place the operator at the end of the line, following the English punctuation rules. ``` var fullHeight = borderTop + innerHeight + borderBottom; ``` Some developers find that placing operators at the beginning of the line makes the code more readable. ``` var fullHeight = borderTop + innerHeight + borderBottom; ``` Rule Details ------------ This rule enforces a consistent linebreak style for operators. Options ------- This rule has two options, a string option and an object option. String option: * `"after"` requires linebreaks to be placed after the operator * `"before"` requires linebreaks to be placed before the operator * `"none"` disallows linebreaks on either side of the operator Object option: * `"overrides"` overrides the global setting for specified operators The default configuration is `"after", { "overrides": { "?": "before", ":": "before" } }` ### after Examples of **incorrect** code for this rule with the `"after"` option: ``` /\*eslint operator-linebreak: ["error", "after"]\*/ foo = 1 + 2; foo = 1 + 2; foo = 5; if (someCondition || otherCondition) { } answer = everything ? 42 : foo; class Foo { a = 1; [b] = 2; [c ] = 3; } ``` Examples of **correct** code for this rule with the `"after"` option: ``` /\*eslint operator-linebreak: ["error", "after"]\*/ foo = 1 + 2; foo = 1 + 2; foo = 5; if (someCondition || otherCondition) { } answer = everything ? 42 : foo; class Foo { a = 1; [b] = 2; [c ] = 3; d = 4; } ``` ### before Examples of **incorrect** code for this rule with the `"before"` option: ``` /\*eslint operator-linebreak: ["error", "before"]\*/ foo = 1 + 2; foo = 5; if (someCondition || otherCondition) { } answer = everything ? 42 : foo; class Foo { a = 1; [b] = 2; [c ] = 3; } ``` Examples of **correct** code for this rule with the `"before"` option: ``` /\*eslint operator-linebreak: ["error", "before"]\*/ foo = 1 + 2; foo = 1 + 2; foo = 5; if (someCondition || otherCondition) { } answer = everything ? 42 : foo; class Foo { a = 1; [b] = 2; [c ] = 3; d = 4; } ``` ### none Examples of **incorrect** code for this rule with the `"none"` option: ``` /\*eslint operator-linebreak: ["error", "none"]\*/ foo = 1 + 2; foo = 1 + 2; if (someCondition || otherCondition) { } if (someCondition || otherCondition) { } answer = everything ? 42 : foo; answer = everything ? 42 : foo; class Foo { a = 1; [b] = 2; [c ] = 3; d = 4; [e] = 5; [f ] = 6; } ``` Examples of **correct** code for this rule with the `"none"` option: ``` /\*eslint operator-linebreak: ["error", "none"]\*/ foo = 1 + 2; foo = 5; if (someCondition || otherCondition) { } answer = everything ? 42 : foo; class Foo { a = 1; [b] = 2; [c ] = 3; d = 4; [e] = 5; [f ] = 6; } ``` ### overrides Examples of additional **incorrect** code for this rule with the `{ "overrides": { "+=": "before" } }` option: ``` /\*eslint operator-linebreak: ["error", "after", { "overrides": { "+=": "before" } }]\*/ var thing = 'thing'; thing += 's'; ``` Examples of additional **correct** code for this rule with the `{ "overrides": { "+=": "before" } }` option: ``` /\*eslint operator-linebreak: ["error", "after", { "overrides": { "+=": "before" } }]\*/ var thing = 'thing'; thing += 's'; ``` Examples of additional **correct** code for this rule with the `{ "overrides": { "?": "ignore", ":": "ignore" } }` option: ``` /\*eslint operator-linebreak: ["error", "after", { "overrides": { "?": "ignore", ":": "ignore" } }]\*/ answer = everything ? 42 : foo; answer = everything ? 42 : foo; ``` Examples of **incorrect** code for this rule with the default `"after", { "overrides": { "?": "before", ":": "before" } }` option: ``` /\*eslint operator-linebreak: ["error", "after", { "overrides": { "?": "before", ":": "before" } }]\*/ foo = 1 + 2; foo = 1 + 2; foo = 5; if (someCondition || otherCondition) { } answer = everything ? 42 : foo; ``` Examples of **correct** code for this rule with the default `"after", { "overrides": { "?": "before", ":": "before" } }` option: ``` /\*eslint operator-linebreak: ["error", "after", { "overrides": { "?": "before", ":": "before" } }]\*/ foo = 1 + 2; foo = 1 + 2; foo = 5; if (someCondition || otherCondition) { } answer = everything ? 42 : foo; ``` When Not To Use It ------------------ If your project will not be using a common operator line break style, turn this rule off. Related Rules ------------- * <comma-style> Version ------- This rule was introduced in ESLint v0.19.0. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/operator-linebreak.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/operator-linebreak.js)
programming_docs
eslint no-empty-function no-empty-function ================= Disallow empty functions Empty functions can reduce readability because readers need to guess whether it’s intentional or not. So writing a clear comment for empty functions is a good practice. ``` function foo() { // do nothing. } ``` Especially, the empty block of arrow functions might be confusing developers. It’s very similar to an empty object literal. ``` list.map(() => {}); // This is a block, would return undefined. list.map(() => ({})); // This is an empty object. ``` Rule Details ------------ This rule is aimed at eliminating empty functions. A function will not be considered a problem if it contains a comment. Examples of **incorrect** code for this rule: ``` /\*eslint no-empty-function: "error"\*/ /\*eslint-env es6\*/ function foo() {} var foo = function() {}; var foo = () => {}; function\* foo() {} var foo = function\*() {}; var obj = { foo: function() {}, foo: function\*() {}, foo() {}, \*foo() {}, get foo() {}, set foo(value) {} }; class A { constructor() {} foo() {} \*foo() {} get foo() {} set foo(value) {} static foo() {} static \*foo() {} static get foo() {} static set foo(value) {} } ``` Examples of **correct** code for this rule: ``` /\*eslint no-empty-function: "error"\*/ /\*eslint-env es6\*/ function foo() { // do nothing. } var foo = function() { // any clear comments. }; var foo = () => { bar(); }; function\* foo() { // do nothing. } var foo = function\*() { // do nothing. }; var obj = { foo: function() { // do nothing. }, foo: function\*() { // do nothing. }, foo() { // do nothing. }, \*foo() { // do nothing. }, get foo() { // do nothing. }, set foo(value) { // do nothing. } }; class A { constructor() { // do nothing. } foo() { // do nothing. } \*foo() { // do nothing. } get foo() { // do nothing. } set foo(value) { // do nothing. } static foo() { // do nothing. } static \*foo() { // do nothing. } static get foo() { // do nothing. } static set foo(value) { // do nothing. } } ``` Options ------- This rule has an option to allow specific kinds of functions to be empty. * `allow` (`string[]`) - A list of kind to allow empty functions. List items are some of the following strings. An empty array (`[]`) by default. + `"functions"` - Normal functions. + `"arrowFunctions"` - Arrow functions. + `"generatorFunctions"` - Generator functions. + `"methods"` - Class methods and method shorthands of object literals. + `"generatorMethods"` - Class methods and method shorthands of object literals with generator. + `"getters"` - Getters. + `"setters"` - Setters. + `"constructors"` - Class constructors. + `"asyncFunctions"` - Async functions. + `"asyncMethods"` - Async class methods and method shorthands of object literals. ### allow: functions Examples of **correct** code for the `{ "allow": ["functions"] }` option: ``` /\*eslint no-empty-function: ["error", { "allow": ["functions"] }]\*/ function foo() {} var foo = function() {}; var obj = { foo: function() {} }; ``` ### allow: arrowFunctions Examples of **correct** code for the `{ "allow": ["arrowFunctions"] }` option: ``` /\*eslint no-empty-function: ["error", { "allow": ["arrowFunctions"] }]\*/ /\*eslint-env es6\*/ var foo = () => {}; ``` ### allow: generatorFunctions Examples of **correct** code for the `{ "allow": ["generatorFunctions"] }` option: ``` /\*eslint no-empty-function: ["error", { "allow": ["generatorFunctions"] }]\*/ /\*eslint-env es6\*/ function\* foo() {} var foo = function\*() {}; var obj = { foo: function\*() {} }; ``` ### allow: methods Examples of **correct** code for the `{ "allow": ["methods"] }` option: ``` /\*eslint no-empty-function: ["error", { "allow": ["methods"] }]\*/ /\*eslint-env es6\*/ var obj = { foo() {} }; class A { foo() {} static foo() {} } ``` ### allow: generatorMethods Examples of **correct** code for the `{ "allow": ["generatorMethods"] }` option: ``` /\*eslint no-empty-function: ["error", { "allow": ["generatorMethods"] }]\*/ /\*eslint-env es6\*/ var obj = { \*foo() {} }; class A { \*foo() {} static \*foo() {} } ``` ### allow: getters Examples of **correct** code for the `{ "allow": ["getters"] }` option: ``` /\*eslint no-empty-function: ["error", { "allow": ["getters"] }]\*/ /\*eslint-env es6\*/ var obj = { get foo() {} }; class A { get foo() {} static get foo() {} } ``` ### allow: setters Examples of **correct** code for the `{ "allow": ["setters"] }` option: ``` /\*eslint no-empty-function: ["error", { "allow": ["setters"] }]\*/ /\*eslint-env es6\*/ var obj = { set foo(value) {} }; class A { set foo(value) {} static set foo(value) {} } ``` ### allow: constructors Examples of **correct** code for the `{ "allow": ["constructors"] }` option: ``` /\*eslint no-empty-function: ["error", { "allow": ["constructors"] }]\*/ /\*eslint-env es6\*/ class A { constructor() {} } ``` ### allow: asyncFunctions Examples of **correct** code for the `{ "allow": ["asyncFunctions"] }` options: ``` /\*eslint no-empty-function: ["error", { "allow": ["asyncFunctions"] }]\*/ /\*eslint-env es2017\*/ async function a(){} ``` ### allow: asyncMethods Examples of **correct** code for the `{ "allow": ["asyncMethods"] }` options: ``` /\*eslint no-empty-function: ["error", { "allow": ["asyncMethods"] }]\*/ /\*eslint-env es2017\*/ var obj = { async foo() {} }; class A { async foo() {} static async foo() {} } ``` When Not To Use It ------------------ If you don’t want to be notified about empty functions, then it’s safe to disable this rule. Related Rules ------------- * <no-empty> Version ------- This rule was introduced in ESLint v2.0.0. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/no-empty-function.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/no-empty-function.js) eslint max-classes-per-file max-classes-per-file ==================== Enforce a maximum number of classes per file Files containing multiple classes can often result in a less navigable and poorly structured codebase. Best practice is to keep each file limited to a single responsibility. Rule Details ------------ This rule enforces that each file may contain only a particular number of classes and no more. Examples of **incorrect** code for this rule: ``` /\*eslint max-classes-per-file: "error"\*/ class Foo {} class Bar {} ``` Examples of **correct** code for this rule: ``` /\*eslint max-classes-per-file: "error"\*/ class Foo {} ``` Options ------- This rule may be configured with either an object or a number. If the option is an object, it may contain one or both of: * `ignoreExpressions`: a boolean option (defaulted to `false`) to ignore class expressions. * `max`: a numeric option (defaulted to 1) to specify the maximum number of classes. For example: ``` { "max-classes-per-file": ["error", 1] } ``` ``` { "max-classes-per-file": [ "error", { "ignoreExpressions": true, "max": 2 } ] } ``` Examples of **correct** code for this rule with the `max` option set to `2`: ``` /\* eslint max-classes-per-file: ["error", 2] \*/ class Foo {} class Bar {} ``` Examples of **correct** code for this rule with the `ignoreExpressions` option set to `true`: ``` /\* eslint max-classes-per-file: ["error", { ignoreExpressions: true }] \*/ class VisitorFactory { forDescriptor(descriptor) { return class { visit(node) { return `Visiting ${descriptor}.`; } }; } } ``` Version ------- This rule was introduced in ESLint v5.0.0-alpha.3. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/max-classes-per-file.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/max-classes-per-file.js) eslint no-mixed-operators no-mixed-operators ================== Disallow mixed binary operators Enclosing complex expressions by parentheses clarifies the developer’s intention, which makes the code more readable. This rule warns when different operators are used consecutively without parentheses in an expression. ``` var foo = a && b || c || d; /\*BAD: Unexpected mix of '&&' and '||'.\*/ var foo = (a && b) || c || d; /\*GOOD\*/ var foo = a && (b || c || d); /\*GOOD\*/ ``` **Note:** It is expected for this rule to emit one error for each mixed operator in a pair. As a result, for each two consecutive mixed operators used, a distinct error will be displayed, pointing to where the specific operator that breaks the rule is used: ``` var foo = a && b || c || d; ``` will generate ``` 1:13 Unexpected mix of '&&' and '||'. (no-mixed-operators) 1:18 Unexpected mix of '&&' and '||'. (no-mixed-operators) ``` Rule Details ------------ This rule checks `BinaryExpression`, `LogicalExpression` and `ConditionalExpression`. This rule may conflict with [no-extra-parens](no-mixed-operatorsno-extra-parens) rule. If you use both this and [no-extra-parens](no-mixed-operatorsno-extra-parens) rule together, you need to use the `nestedBinaryExpressions` option of [no-extra-parens](no-mixed-operatorsno-extra-parens) rule. Examples of **incorrect** code for this rule: ``` /\*eslint no-mixed-operators: "error"\*/ var foo = a && b < 0 || c > 0 || d + 1 === 0; var foo = a + b \* c; ``` Examples of **correct** code for this rule: ``` /\*eslint no-mixed-operators: "error"\*/ var foo = a || b || c; var foo = a && b && c; var foo = (a && b < 0) || c > 0 || d + 1 === 0; var foo = a && (b < 0 || c > 0 || d + 1 === 0); var foo = a + (b \* c); var foo = (a + b) \* c; ``` Options ------- ``` { "no-mixed-operators": [ "error", { "groups": [ ["+", "-", "\*", "/", "%", "\*\*"], ["&", "|", "^", "~", "<<", ">>", ">>>"], ["==", "!=", "===", "!==", ">", ">=", "<", "<="], ["&&", "||"], ["in", "instanceof"] ], "allowSamePrecedence": true } ] } ``` This rule has 2 options. * `groups` (`string[][]`) - specifies operator groups to be checked. The `groups` option is a list of groups, and a group is a list of binary operators. Default operator groups are defined as arithmetic, bitwise, comparison, logical, and relational operators. Note: Ternary operator(?:) can be part of any group and by default is allowed to be mixed with other operators. * `allowSamePrecedence` (`boolean`) - specifies whether to allow mixed operators if they are of equal precedence. Default is `true`. ### groups The following operators can be used in `groups` option: * Arithmetic Operators: `"+"`, `"-"`, `"*"`, `"/"`, `"%"`, `"**"` * Bitwise Operators: `"&"`, `"|"`, `"^"`, `"~"`, `"<<"`, `">>"`, `">>>"` * Comparison Operators: `"=="`, `"!="`, `"==="`, `"!=="`, `">"`, `">="`, `"<"`, `"<="` * Logical Operators: `"&&"`, `"||"` * Coalesce Operator: `"??"` * Relational Operators: `"in"`, `"instanceof"` * Ternary Operator: `?:` Now, consider the following group configuration: `{"groups": [["&", "|", "^", "~", "<<", ">>", ">>>"], ["&&", "||"]]}`. There are 2 groups specified in this configuration: bitwise operators and logical operators. This rule checks if the operators belong to the same group only. In this case, this rule checks if bitwise operators and logical operators are mixed, but ignores all other operators. Examples of **incorrect** code for this rule with `{"groups": [["&", "|", "^", "~", "<<", ">>", ">>>"], ["&&", "||"]]}` option: ``` /\*eslint no-mixed-operators: ["error", {"groups": [["&", "|", "^", "~", "<<", ">>", ">>>"], ["&&", "||"]]}]\*/ var foo = a && b < 0 || c > 0 || d + 1 === 0; var foo = a & b | c; ``` ``` /\*eslint no-mixed-operators: ["error", {"groups": [["&&", "||", "?:"]]}]\*/ var foo = a || b ? c : d; var bar = a ? b || c : d; var baz = a ? b : c || d; ``` Examples of **correct** code for this rule with `{"groups": [["&", "|", "^", "~", "<<", ">>", ">>>"], ["&&", "||"]]}` option: ``` /\*eslint no-mixed-operators: ["error", {"groups": [["&", "|", "^", "~", "<<", ">>", ">>>"], ["&&", "||"]]}]\*/ var foo = a || b > 0 || c + 1 === 0; var foo = a && b > 0 && c + 1 === 0; var foo = (a && b < 0) || c > 0 || d + 1 === 0; var foo = a && (b < 0 || c > 0 || d + 1 === 0); var foo = (a & b) | c; var foo = a & (b | c); var foo = a + b \* c; var foo = a + (b \* c); var foo = (a + b) \* c; ``` ``` /\*eslint no-mixed-operators: ["error", {"groups": [["&&", "||", "?:"]]}]\*/ var foo = (a || b) ? c : d; var foo = a || (b ? c : d); var bar = a ? (b || c) : d; var baz = a ? b : (c || d); var baz = (a ? b : c) || d; ``` ### allowSamePrecedence Examples of **correct** code for this rule with `{"allowSamePrecedence": true}` option: ``` /\*eslint no-mixed-operators: ["error", {"allowSamePrecedence": true}]\*/ // + and - have the same precedence. var foo = a + b - c; ``` Examples of **incorrect** code for this rule with `{"allowSamePrecedence": false}` option: ``` /\*eslint no-mixed-operators: ["error", {"allowSamePrecedence": false}]\*/ // + and - have the same precedence. var foo = a + b - c; ``` Examples of **correct** code for this rule with `{"allowSamePrecedence": false}` option: ``` /\*eslint no-mixed-operators: ["error", {"allowSamePrecedence": false}]\*/ // + and - have the same precedence. var foo = (a + b) - c; ``` When Not To Use It ------------------ If you don’t want to be notified about mixed operators, then it’s safe to disable this rule. Related Rules ------------- * <no-extra-parens> Version ------- This rule was introduced in ESLint v2.12.0. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/no-mixed-operators.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/no-mixed-operators.js) eslint object-property-newline object-property-newline ======================= Enforce placing object properties on separate lines 🔧 Fixable Some problems reported by this rule are automatically fixable by the `--fix` [command line](object-property-newline../user-guide/command-line-interface#--fix) option This rule permits you to restrict the locations of property specifications in object literals. You may prohibit any part of any property specification from appearing on the same line as any part of any other property specification. You may make this prohibition absolute, or, by invoking an object option, you may allow an exception, permitting an object literal to have all parts of all of its property specifications on a single line. Rule Details ------------ ### Motivations This rule makes it possible to ensure, as some style guides require, that property specifications appear on separate lines for better readability. For example, you can prohibit all of these: ``` const newObject = {a: 1, b: [2, {a: 3, b: 4}]}; const newObject = { a: 1, b: [2, {a: 3, b: 4}] }; const newObject = { a: 1, b: [2, {a: 3, b: 4}] }; const newObject = { a: 1, b: [ 2, {a: 3, b: 4} ] }; ``` Instead of those, you can comply with the rule by writing ``` const newObject = { a: 1, b: [2, { a: 3, b: 4 }] }; ``` or ``` const newObject = { a: 1, b: [ 2, { a: 3, b: 4 } ] }; ``` Another benefit of this rule is specificity of diffs when a property is changed: ``` // More specific var obj = { foo: "foo", - bar: "bar", + bar: "bazz", baz: "baz" }; ``` ``` // Less specific -var obj = { foo: "foo", bar: "bar", baz: "baz" }; +var obj = { foo: "foo", bar: "bazz", baz: "baz" }; ``` ### Optional Exception The rule offers one object option, `allowAllPropertiesOnSameLine` (a deprecated synonym is `allowMultiplePropertiesPerLine`). If you set it to `true`, object literals such as the first two above, with all property specifications on the same line, will be permitted, but one like ``` const newObject = { a: 'a.m.', b: 'p.m.', c: 'daylight saving time' }; ``` will be prohibited, because two properties, but not all properties, appear on the same line. ### Notations This rule applies equally to all property specifications, regardless of notation, including: * `a: 1` (ES5) * `a` (ES2015 shorthand property) * `[`prop${a}`]` (ES2015 computed property name) Thus, the rule (without the optional exception) prohibits both of these: ``` const newObject = { a: 1, [ process.argv[4] ]: '01' }; const newObject = { a: 1, [process.argv[4]]: '01' }; ``` (This behavior differs from that of the JSCS rule cited below, which does not treat the leading `[` of a computed property name as part of that property specification. The JSCS rule prohibits the second of these formats but permits the first.) ### Multiline Properties The rule prohibits the colocation on any line of at least 1 character of one property specification with at least 1 character of any other property specification. For example, the rule prohibits ``` const newObject = {a: [ 'Officiële website van de Europese Unie', 'Официален уебсайт на Европейския съюз' ], b: 2}; ``` because 1 character of the specification of `a` (i.e. the trailing `]` of its value) is on the same line as the specification of `b`. The optional exception does not excuse this case, because the entire collection of property specifications spans 4 lines, not 1. ### Inter-property Delimiters The comma and any whitespace that delimit property specifications are not considered parts of them. Therefore, the rule permits both of these formats: ``` const newFunction = multiplier => ({ a: 2 \* multiplier, b: 4 \* multiplier, c: 8 \* multiplier }); const newFunction = multiplier => ({ a: 2 \* multiplier , b: 4 \* multiplier , c: 8 \* multiplier }); ``` (This behavior differs from that of the JSCS rule cited below, which permits the first but prohibits the second format.) ### –fix If this rule is invoked with the command-line `--fix` option, object literals that violate the rule are generally modified to comply with it. The modification in each case is to move a property specification to the next line whenever there is part or all of a previous property specification on the same line. For example, ``` const newObject = { a: 'a.m.', b: 'p.m.', c: 'daylight saving time' }; ``` is converted to ``` const newObject = { a: 'a.m.', b: 'p.m.', c: 'daylight saving time' }; ``` The modification does not depend on whether the object option is set to `true`. In other words, ESLint never collects all the property specifications onto a single line, even when the object option would permit that. ESLint does not correct a violation of this rule if a comment immediately precedes the second or subsequent property specification on a line, since ESLint cannot determine which line to put the comment onto. As illustrated above, the `--fix` option, applied to this rule, does not comply with other rules, such as `indent`, but, if those other rules are also in effect, the option applies them, too. Examples -------- Examples of **incorrect** code for this rule, with no object option or with `allowAllPropertiesOnSameLine` set to `false`: ``` /\*eslint object-property-newline: "error"\*/ const obj0 = { foo: "foo", bar: "bar", baz: "baz" }; const obj1 = { foo: "foo", bar: "bar", baz: "baz" }; const obj2 = { foo: "foo", bar: "bar", baz: "baz" }; const obj3 = { [process.argv[3] ? "foo" : "bar"]: 0, baz: [ 1, 2, 4, 8 ] }; const a = "antidisestablishmentarianistically"; const b = "yugoslavyalılaştırabildiklerimizdenmişsiniz"; const obj4 = {a, b}; const domain = process.argv[4]; const obj5 = { foo: "foo", [ domain.includes(":") ? "complexdomain" : "simpledomain" ]: true}; ``` Examples of **correct** code for this rule, with no object option or with `allowAllPropertiesOnSameLine` set to `false`: ``` /\*eslint object-property-newline: "error"\*/ const obj1 = { foo: "foo", bar: "bar", baz: "baz" }; const obj2 = { foo: "foo" , bar: "bar" , baz: "baz" }; const user = process.argv[2]; const obj3 = { user, [process.argv[3] ? "foo" : "bar"]: 0, baz: [ 1, 2, 4, 8 ] }; ``` Examples of additional **correct** code for this rule with the `{ "allowAllPropertiesOnSameLine": true }` option: ``` /\*eslint object-property-newline: ["error", { "allowAllPropertiesOnSameLine": true }]\*/ const obj = { foo: "foo", bar: "bar", baz: "baz" }; const obj2 = { foo: "foo", bar: "bar", baz: "baz" }; const user = process.argv[2]; const obj3 = { user, [process.argv[3] ? "foo" : "bar"]: 0, baz: [1, 2, 4, 8] }; ``` When Not To Use It ------------------ You can turn this rule off if you want to decide, case-by-case, whether to place property specifications on separate lines. Compatibility ------------- * **JSCS**: This rule provides partial compatibility with [requireObjectKeysOnNewLine](https://jscs-dev.github.io/rule/requireObjectKeysOnNewLine). Related Rules ------------- * <brace-style> * <comma-dangle> * <key-spacing> * <object-curly-spacing> Version ------- This rule was introduced in ESLint v2.10.0. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/object-property-newline.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/object-property-newline.js)
programming_docs
eslint indent indent ====== Enforce consistent indentation 🔧 Fixable Some problems reported by this rule are automatically fixable by the `--fix` [command line](indent../user-guide/command-line-interface#--fix) option There are several common guidelines which require specific indentation of nested blocks and statements, like: ``` function hello(indentSize, type) { if (indentSize === 4 && type !== 'tab') { console.log('Each next indentation will increase on 4 spaces'); } } ``` These are the most common scenarios recommended in different style guides: * Two spaces, not longer and no tabs: Google, npm, Node.js, Idiomatic, Felix * Tabs: jQuery * Four spaces: Crockford Rule Details ------------ This rule enforces a consistent indentation style. The default style is `4 spaces`. Options ------- This rule has a mixed option: For example, for 2-space indentation: ``` { "indent": ["error", 2] } ``` Or for tabbed indentation: ``` { "indent": ["error", "tab"] } ``` Examples of **incorrect** code for this rule with the default options: ``` /\*eslint indent: "error"\*/ if (a) { b=c; function foo(d) { e=f; } } ``` Examples of **correct** code for this rule with the default options: ``` /\*eslint indent: "error"\*/ if (a) { b=c; function foo(d) { e=f; } } ``` This rule has an object option: * `"ignoredNodes"` can be used to disable indentation checking for any AST node. This accepts an array of [selectors](indent../developer-guide/selectors). If an AST node is matched by any of the selectors, the indentation of tokens which are direct children of that node will be ignored. This can be used as an escape hatch to relax the rule if you disagree with the indentation that it enforces for a particular syntactic pattern. * `"SwitchCase"` (default: 0) enforces indentation level for `case` clauses in `switch` statements * `"VariableDeclarator"` (default: 1) enforces indentation level for `var` declarators; can also take an object to define separate rules for `var`, `let` and `const` declarations. It can also be `"first"`, indicating all the declarators should be aligned with the first declarator. * `"outerIIFEBody"` (default: 1) enforces indentation level for file-level IIFEs. This can also be set to `"off"` to disable checking for file-level IIFEs. * `"MemberExpression"` (default: 1) enforces indentation level for multi-line property chains. This can also be set to `"off"` to disable checking for MemberExpression indentation. * `"FunctionDeclaration"` takes an object to define rules for function declarations. + `parameters` (default: 1) enforces indentation level for parameters in a function declaration. This can either be a number indicating indentation level, or the string `"first"` indicating that all parameters of the declaration must be aligned with the first parameter. This can also be set to `"off"` to disable checking for FunctionDeclaration parameters. + `body` (default: 1) enforces indentation level for the body of a function declaration. * `"FunctionExpression"` takes an object to define rules for function expressions. + `parameters` (default: 1) enforces indentation level for parameters in a function expression. This can either be a number indicating indentation level, or the string `"first"` indicating that all parameters of the expression must be aligned with the first parameter. This can also be set to `"off"` to disable checking for FunctionExpression parameters. + `body` (default: 1) enforces indentation level for the body of a function expression. * `"StaticBlock"` takes an object to define rules for class static blocks. + `body` (default: 1) enforces indentation level for the body of a class static block. * `"CallExpression"` takes an object to define rules for function call expressions. + `arguments` (default: 1) enforces indentation level for arguments in a call expression. This can either be a number indicating indentation level, or the string `"first"` indicating that all arguments of the expression must be aligned with the first argument. This can also be set to `"off"` to disable checking for CallExpression arguments. * `"ArrayExpression"` (default: 1) enforces indentation level for elements in arrays. It can also be set to the string `"first"`, indicating that all the elements in the array should be aligned with the first element. This can also be set to `"off"` to disable checking for array elements. * `"ObjectExpression"` (default: 1) enforces indentation level for properties in objects. It can be set to the string `"first"`, indicating that all properties in the object should be aligned with the first property. This can also be set to `"off"` to disable checking for object properties. * `"ImportDeclaration"` (default: 1) enforces indentation level for import statements. It can be set to the string `"first"`, indicating that all imported members from a module should be aligned with the first member in the list. This can also be set to `"off"` to disable checking for imported module members. * `"flatTernaryExpressions": true` (`false` by default) requires no indentation for ternary expressions which are nested in other ternary expressions. * `"offsetTernaryExpressions": true` (`false` by default) requires indentation for values of ternary expressions. * `"ignoreComments"` (default: false) can be used when comments do not need to be aligned with nodes on the previous or next line. Level of indentation denotes the multiple of the indent specified. Example: * Indent of 4 spaces with `VariableDeclarator` set to `2` will indent the multi-line variable declarations with 8 spaces. * Indent of 2 spaces with `VariableDeclarator` set to `2` will indent the multi-line variable declarations with 4 spaces. * Indent of 2 spaces with `VariableDeclarator` set to `{"var": 2, "let": 2, "const": 3}` will indent the multi-line variable declarations with 4 spaces for `var` and `let`, 6 spaces for `const` statements. * Indent of tab with `VariableDeclarator` set to `2` will indent the multi-line variable declarations with 2 tabs. * Indent of 2 spaces with `SwitchCase` set to `0` will not indent `case` clauses with respect to `switch` statements. * Indent of 2 spaces with `SwitchCase` set to `1` will indent `case` clauses with 2 spaces with respect to `switch` statements. * Indent of 2 spaces with `SwitchCase` set to `2` will indent `case` clauses with 4 spaces with respect to `switch` statements. * Indent of tab with `SwitchCase` set to `2` will indent `case` clauses with 2 tabs with respect to `switch` statements. * Indent of 2 spaces with `MemberExpression` set to `0` will indent the multi-line property chains with 0 spaces. * Indent of 2 spaces with `MemberExpression` set to `1` will indent the multi-line property chains with 2 spaces. * Indent of 2 spaces with `MemberExpression` set to `2` will indent the multi-line property chains with 4 spaces. * Indent of 4 spaces with `MemberExpression` set to `0` will indent the multi-line property chains with 0 spaces. * Indent of 4 spaces with `MemberExpression` set to `1` will indent the multi-line property chains with 4 spaces. * Indent of 4 spaces with `MemberExpression` set to `2` will indent the multi-line property chains with 8 spaces. ### tab Examples of **incorrect** code for this rule with the `"tab"` option: ``` /\*eslint indent: ["error", "tab"]\*/ if (a) { b=c; function foo(d) { e=f; } } ``` Examples of **correct** code for this rule with the `"tab"` option: ``` /\*eslint indent: ["error", "tab"]\*/ if (a) { /\*tab\*/b=c; /\*tab\*/function foo(d) { /\*tab\*//\*tab\*/e=f; /\*tab\*/} } ``` ### ignoredNodes The following configuration ignores the indentation of `ConditionalExpression` (“ternary expression”) nodes: Examples of **correct** code for this rule with the `4, { "ignoredNodes": ["ConditionalExpression"] }` option: ``` /\*eslint indent: ["error", 4, { "ignoredNodes": ["ConditionalExpression"] }]\*/ var a = foo ? bar : baz; var a = foo ? bar : baz; ``` The following configuration ignores indentation in the body of IIFEs. Examples of **correct** code for this rule with the `4, { "ignoredNodes": ["CallExpression > FunctionExpression.callee > BlockStatement.body"] }` option: ``` /\*eslint indent: ["error", 4, { "ignoredNodes": ["CallExpression > FunctionExpression.callee > BlockStatement.body"] }]\*/ (function() { foo(); bar(); }) ``` All AST node types can be found at [ESTree](https://github.com/estree/estree) specification. You can use [AST Explorer](https://astexplorer.net/) with the espree parser to examine AST tree of a code snippet. ### SwitchCase Examples of **incorrect** code for this rule with the `2, { "SwitchCase": 1 }` options: ``` /\*eslint indent: ["error", 2, { "SwitchCase": 1 }]\*/ switch(a){ case "a": break; case "b": break; } ``` Examples of **correct** code for this rule with the `2, { "SwitchCase": 1 }` option: ``` /\*eslint indent: ["error", 2, { "SwitchCase": 1 }]\*/ switch(a){ case "a": break; case "b": break; } ``` ### VariableDeclarator Examples of **incorrect** code for this rule with the `2, { "VariableDeclarator": 1 }` options: ``` /\*eslint indent: ["error", 2, { "VariableDeclarator": 1 }]\*/ /\*eslint-env es6\*/ var a, b, c; let a, b, c; const a = 1, b = 2, c = 3; ``` Examples of **correct** code for this rule with the `2, { "VariableDeclarator": 1 }` options: ``` /\*eslint indent: ["error", 2, { "VariableDeclarator": 1 }]\*/ /\*eslint-env es6\*/ var a, b, c; let a, b, c; const a = 1, b = 2, c = 3; ``` Examples of **correct** code for this rule with the `2, { "VariableDeclarator": 2 }` options: ``` /\*eslint indent: ["error", 2, { "VariableDeclarator": 2 }]\*/ /\*eslint-env es6\*/ var a, b, c; let a, b, c; const a = 1, b = 2, c = 3; ``` Examples of **incorrect** code for this rule with the `2, { "VariableDeclarator": "first" }` options: ``` /\*eslint indent: ["error", 2, { "VariableDeclarator": "first" }]\*/ /\*eslint-env es6\*/ var a, b, c; let a, b, c; const a = 1, b = 2, c = 3; ``` Examples of **correct** code for this rule with the `2, { "VariableDeclarator": "first" }` options: ``` /\*eslint indent: ["error", 2, { "VariableDeclarator": "first" }]\*/ /\*eslint-env es6\*/ var a, b, c; let a, b, c; const a = 1, b = 2, c = 3; ``` Examples of **correct** code for this rule with the `2, { "VariableDeclarator": { "var": 2, "let": 2, "const": 3 } }` options: ``` /\*eslint indent: ["error", 2, { "VariableDeclarator": { "var": 2, "let": 2, "const": 3 } }]\*/ /\*eslint-env es6\*/ var a, b, c; let a, b, c; const a = 1, b = 2, c = 3; ``` ### outerIIFEBody Examples of **incorrect** code for this rule with the options `2, { "outerIIFEBody": 0 }`: ``` /\*eslint indent: ["error", 2, { "outerIIFEBody": 0 }]\*/ (function() { function foo(x) { return x + 1; } })(); if (y) { console.log('foo'); } ``` Examples of **correct** code for this rule with the options `2, { "outerIIFEBody": 0 }`: ``` /\*eslint indent: ["error", 2, { "outerIIFEBody": 0 }]\*/ (function() { function foo(x) { return x + 1; } })(); if (y) { console.log('foo'); } ``` Examples of **correct** code for this rule with the options `2, { "outerIIFEBody": "off" }`: ``` /\*eslint indent: ["error", 2, { "outerIIFEBody": "off" }]\*/ (function() { function foo(x) { return x + 1; } })(); (function() { function foo(x) { return x + 1; } })(); if (y) { console.log('foo'); } ``` ### MemberExpression Examples of **incorrect** code for this rule with the `2, { "MemberExpression": 1 }` options: ``` /\*eslint indent: ["error", 2, { "MemberExpression": 1 }]\*/ foo .bar .baz() ``` Examples of **correct** code for this rule with the `2, { "MemberExpression": 1 }` option: ``` /\*eslint indent: ["error", 2, { "MemberExpression": 1 }]\*/ foo .bar .baz(); ``` ### FunctionDeclaration Examples of **incorrect** code for this rule with the `2, { "FunctionDeclaration": {"body": 1, "parameters": 2} }` option: ``` /\*eslint indent: ["error", 2, { "FunctionDeclaration": {"body": 1, "parameters": 2} }]\*/ function foo(bar, baz, qux) { qux(); } ``` Examples of **correct** code for this rule with the `2, { "FunctionDeclaration": {"body": 1, "parameters": 2} }` option: ``` /\*eslint indent: ["error", 2, { "FunctionDeclaration": {"body": 1, "parameters": 2} }]\*/ function foo(bar, baz, qux) { qux(); } ``` Examples of **incorrect** code for this rule with the `2, { "FunctionDeclaration": {"parameters": "first"} }` option: ``` /\*eslint indent: ["error", 2, {"FunctionDeclaration": {"parameters": "first"}}]\*/ function foo(bar, baz, qux, boop) { qux(); } ``` Examples of **correct** code for this rule with the `2, { "FunctionDeclaration": {"parameters": "first"} }` option: ``` /\*eslint indent: ["error", 2, {"FunctionDeclaration": {"parameters": "first"}}]\*/ function foo(bar, baz, qux, boop) { qux(); } ``` ### FunctionExpression Examples of **incorrect** code for this rule with the `2, { "FunctionExpression": {"body": 1, "parameters": 2} }` option: ``` /\*eslint indent: ["error", 2, { "FunctionExpression": {"body": 1, "parameters": 2} }]\*/ var foo = function(bar, baz, qux) { qux(); } ``` Examples of **correct** code for this rule with the `2, { "FunctionExpression": {"body": 1, "parameters": 2} }` option: ``` /\*eslint indent: ["error", 2, { "FunctionExpression": {"body": 1, "parameters": 2} }]\*/ var foo = function(bar, baz, qux) { qux(); } ``` Examples of **incorrect** code for this rule with the `2, { "FunctionExpression": {"parameters": "first"} }` option: ``` /\*eslint indent: ["error", 2, {"FunctionExpression": {"parameters": "first"}}]\*/ var foo = function(bar, baz, qux, boop) { qux(); } ``` Examples of **correct** code for this rule with the `2, { "FunctionExpression": {"parameters": "first"} }` option: ``` /\*eslint indent: ["error", 2, {"FunctionExpression": {"parameters": "first"}}]\*/ var foo = function(bar, baz, qux, boop) { qux(); } ``` ### StaticBlock Examples of **incorrect** code for this rule with the `2, { "StaticBlock": {"body": 1} }` option: ``` /\*eslint indent: ["error", 2, { "StaticBlock": {"body": 1} }]\*/ class C { static { foo(); } } ``` Examples of **correct** code for this rule with the `2, { "StaticBlock": {"body": 1} }` option: ``` /\*eslint indent: ["error", 2, { "StaticBlock": {"body": 1} }]\*/ class C { static { foo(); } } ``` Examples of **incorrect** code for this rule with the `2, { "StaticBlock": {"body": 2} }` option: ``` /\*eslint indent: ["error", 2, { "StaticBlock": {"body": 2} }]\*/ class C { static { foo(); } } ``` Examples of **correct** code for this rule with the `2, { "StaticBlock": {"body": 2} }` option: ``` /\*eslint indent: ["error", 2, { "StaticBlock": {"body": 2} }]\*/ class C { static { foo(); } } ``` ### CallExpression Examples of **incorrect** code for this rule with the `2, { "CallExpression": {"arguments": 1} }` option: ``` /\*eslint indent: ["error", 2, { "CallExpression": {"arguments": 1} }]\*/ foo(bar, baz, qux ); ``` Examples of **correct** code for this rule with the `2, { "CallExpression": {"arguments": 1} }` option: ``` /\*eslint indent: ["error", 2, { "CallExpression": {"arguments": 1} }]\*/ foo(bar, baz, qux ); ``` Examples of **incorrect** code for this rule with the `2, { "CallExpression": {"arguments": "first"} }` option: ``` /\*eslint indent: ["error", 2, {"CallExpression": {"arguments": "first"}}]\*/ foo(bar, baz, baz, boop, beep); ``` Examples of **correct** code for this rule with the `2, { "CallExpression": {"arguments": "first"} }` option: ``` /\*eslint indent: ["error", 2, {"CallExpression": {"arguments": "first"}}]\*/ foo(bar, baz, baz, boop, beep); ``` ### ArrayExpression Examples of **incorrect** code for this rule with the `2, { "ArrayExpression": 1 }` option: ``` /\*eslint indent: ["error", 2, { "ArrayExpression": 1 }]\*/ var foo = [ bar, baz, qux ]; ``` Examples of **correct** code for this rule with the `2, { "ArrayExpression": 1 }` option: ``` /\*eslint indent: ["error", 2, { "ArrayExpression": 1 }]\*/ var foo = [ bar, baz, qux ]; ``` Examples of **incorrect** code for this rule with the `2, { "ArrayExpression": "first" }` option: ``` /\*eslint indent: ["error", 2, {"ArrayExpression": "first"}]\*/ var foo = [bar, baz, qux ]; ``` Examples of **correct** code for this rule with the `2, { "ArrayExpression": "first" }` option: ``` /\*eslint indent: ["error", 2, {"ArrayExpression": "first"}]\*/ var foo = [bar, baz, qux ]; ``` ### ObjectExpression Examples of **incorrect** code for this rule with the `2, { "ObjectExpression": 1 }` option: ``` /\*eslint indent: ["error", 2, { "ObjectExpression": 1 }]\*/ var foo = { bar: 1, baz: 2, qux: 3 }; ``` Examples of **correct** code for this rule with the `2, { "ObjectExpression": 1 }` option: ``` /\*eslint indent: ["error", 2, { "ObjectExpression": 1 }]\*/ var foo = { bar: 1, baz: 2, qux: 3 }; ``` Examples of **incorrect** code for this rule with the `2, { "ObjectExpression": "first" }` option: ``` /\*eslint indent: ["error", 2, {"ObjectExpression": "first"}]\*/ var foo = { bar: 1, baz: 2 }; ``` Examples of **correct** code for this rule with the `2, { "ObjectExpression": "first" }` option: ``` /\*eslint indent: ["error", 2, {"ObjectExpression": "first"}]\*/ var foo = { bar: 1, baz: 2 }; ``` ### ImportDeclaration Examples of **correct** code for this rule with the `4, { "ImportDeclaration": 1 }` option (the default): ``` /\*eslint indent: ["error", 4, { "ImportDeclaration": 1 }]\*/ import { foo, bar, baz, } from 'qux'; import { foo, bar, baz, } from 'qux'; ``` Examples of **incorrect** code for this rule with the `4, { "ImportDeclaration": "first" }` option: ``` /\*eslint indent: ["error", 4, { "ImportDeclaration": "first" }]\*/ import { foo, bar, baz, } from 'qux'; ``` Examples of **correct** code for this rule with the `4, { "ImportDeclaration": "first" }` option: ``` /\*eslint indent: ["error", 4, { "ImportDeclaration": "first" }]\*/ import { foo, bar, baz, } from 'qux'; ``` ### flatTernaryExpressions Examples of **incorrect** code for this rule with the default `4, { "flatTernaryExpressions": false }` option: ``` /\*eslint indent: ["error", 4, { "flatTernaryExpressions": false }]\*/ var a = foo ? bar : baz ? qux : boop; ``` Examples of **correct** code for this rule with the default `4, { "flatTernaryExpressions": false }` option: ``` /\*eslint indent: ["error", 4, { "flatTernaryExpressions": false }]\*/ var a = foo ? bar : baz ? qux : boop; ``` Examples of **incorrect** code for this rule with the `4, { "flatTernaryExpressions": true }` option: ``` /\*eslint indent: ["error", 4, { "flatTernaryExpressions": true }]\*/ var a = foo ? bar : baz ? qux : boop; ``` Examples of **correct** code for this rule with the `4, { "flatTernaryExpressions": true }` option: ``` /\*eslint indent: ["error", 4, { "flatTernaryExpressions": true }]\*/ var a = foo ? bar : baz ? qux : boop; ``` ### offsetTernaryExpressions Examples of **incorrect** code for this rule with the default `2, { "offsetTernaryExpressions": false }` option: ``` /\*eslint indent: ["error", 2, { "offsetTernaryExpressions": false }]\*/ condition ? () => { return true } : () => { false } ``` Examples of **correct** code for this rule with the default `2, { "offsetTernaryExpressions": false }` option: ``` /\*eslint indent: ["error", 2, { "offsetTernaryExpressions": false }]\*/ condition ? () => { return true } : condition2 ? () => { return true } : () => { return false } ``` Examples of **incorrect** code for this rule with the `2, { "offsetTernaryExpressions": true }` option: ``` /\*eslint indent: ["error", 2, { "offsetTernaryExpressions": true }]\*/ condition ? () => { return true } : condition2 ? () => { return true } : () => { return false } ``` Examples of **correct** code for this rule with the `2, { "offsetTernaryExpressions": true }` option: ``` /\*eslint indent: ["error", 2, { "offsetTernaryExpressions": true }]\*/ condition ? () => { return true } : condition2 ? () => { return true } : () => { return false } ``` ### ignoreComments Examples of additional **correct** code for this rule with the `4, { "ignoreComments": true }` option: ``` /\*eslint indent: ["error", 4, { "ignoreComments": true }] \*/ if (foo) { doSomething(); // comment intentionally de-indented doSomethingElse(); } ``` Compatibility ------------- * **JSHint**: `indent` * **JSCS**: [validateIndentation](https://jscs-dev.github.io/rule/validateIndentation) Version ------- This rule was introduced in ESLint v0.14.0. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/indent.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/indent.js)
programming_docs
eslint no-octal-escape no-octal-escape =============== Disallow octal escape sequences in string literals As of the ECMAScript 5 specification, octal escape sequences in string literals are deprecated and should not be used. Unicode escape sequences should be used instead. ``` var foo = "Copyright \251"; ``` Rule Details ------------ This rule disallows octal escape sequences in string literals. If ESLint parses code in strict mode, the parser (instead of this rule) reports the error. Examples of **incorrect** code for this rule: ``` /\*eslint no-octal-escape: "error"\*/ var foo = "Copyright \251"; ``` Examples of **correct** code for this rule: ``` /\*eslint no-octal-escape: "error"\*/ var foo = "Copyright \u00A9"; // unicode var foo = "Copyright \xA9"; // hexadecimal ``` Version ------- This rule was introduced in ESLint v0.0.9. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/no-octal-escape.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/no-octal-escape.js) eslint arrow-body-style arrow-body-style ================ Require braces around arrow function bodies 🔧 Fixable Some problems reported by this rule are automatically fixable by the `--fix` [command line](arrow-body-style../user-guide/command-line-interface#--fix) option Arrow functions have two syntactic forms for their function bodies. They may be defined with a *block* body (denoted by curly braces) `() => { ... }` or with a single expression `() => ...`, whose value is implicitly returned. Rule Details ------------ This rule can enforce or disallow the use of braces around arrow function body. Options ------- The rule takes one or two options. The first is a string, which can be: * `"always"` enforces braces around the function body * `"as-needed"` enforces no braces where they can be omitted (default) * `"never"` enforces no braces around the function body (constrains arrow functions to the role of returning an expression) The second one is an object for more fine-grained configuration when the first option is `"as-needed"`. Currently, the only available option is `requireReturnForObjectLiteral`, a boolean property. It’s `false` by default. If set to `true`, it requires braces and an explicit return for object literals. ``` "arrow-body-style": ["error", "always"] ``` ### always Examples of **incorrect** code for this rule with the `"always"` option: ``` /\*eslint arrow-body-style: ["error", "always"]\*/ /\*eslint-env es6\*/ let foo = () => 0; ``` Examples of **correct** code for this rule with the `"always"` option: ``` let foo = () => { return 0; }; let foo = (retv, name) => { retv[name] = true; return retv; }; ``` ### as-needed Examples of **incorrect** code for this rule with the default `"as-needed"` option: ``` /\*eslint arrow-body-style: ["error", "as-needed"]\*/ /\*eslint-env es6\*/ let foo = () => { return 0; }; let foo = () => { return { bar: { foo: 1, bar: 2, } }; }; ``` Examples of **correct** code for this rule with the default `"as-needed"` option: ``` /\*eslint arrow-body-style: ["error", "as-needed"]\*/ /\*eslint-env es6\*/ let foo = () => 0; let foo = (retv, name) => { retv[name] = true; return retv; }; let foo = () => ({ bar: { foo: 1, bar: 2, } }); let foo = () => { bar(); }; let foo = () => {}; let foo = () => { /\* do nothing \*/ }; let foo = () => { // do nothing. }; let foo = () => ({ bar: 0 }); ``` #### requireReturnForObjectLiteral > This option is only applicable when used in conjunction with the `"as-needed"` option. > > Examples of **incorrect** code for this rule with the `{ "requireReturnForObjectLiteral": true }` option: ``` /\*eslint arrow-body-style: ["error", "as-needed", { "requireReturnForObjectLiteral": true }]\*/ /\*eslint-env es6\*/ let foo = () => ({}); let foo = () => ({ bar: 0 }); ``` Examples of **correct** code for this rule with the `{ "requireReturnForObjectLiteral": true }` option: ``` /\*eslint arrow-body-style: ["error", "as-needed", { "requireReturnForObjectLiteral": true }]\*/ /\*eslint-env es6\*/ let foo = () => {}; let foo = () => { return { bar: 0 }; }; ``` ### never Examples of **incorrect** code for this rule with the `"never"` option: ``` /\*eslint arrow-body-style: ["error", "never"]\*/ /\*eslint-env es6\*/ let foo = () => { return 0; }; let foo = (retv, name) => { retv[name] = true; return retv; }; ``` Examples of **correct** code for this rule with the `"never"` option: ``` /\*eslint arrow-body-style: ["error", "never"]\*/ /\*eslint-env es6\*/ let foo = () => 0; let foo = () => ({ foo: 0 }); ``` Version ------- This rule was introduced in ESLint v1.8.0. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/arrow-body-style.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/arrow-body-style.js) eslint yield-star-spacing yield-star-spacing ================== Require or disallow spacing around the `*` in `yield*` expressions 🔧 Fixable Some problems reported by this rule are automatically fixable by the `--fix` [command line](yield-star-spacing../user-guide/command-line-interface#--fix) option Rule Details ------------ This rule enforces spacing around the `*` in `yield*` expressions. Options ------- The rule takes one option, an object, which has two keys `before` and `after` having boolean values `true` or `false`. * `before` enforces spacing between the `yield` and the `*`. If `true`, a space is required, otherwise spaces are disallowed. * `after` enforces spacing between the `*` and the argument. If it is `true`, a space is required, otherwise spaces are disallowed. The default is `{"before": false, "after": true}`. ``` "yield-star-spacing": ["error", {"before": true, "after": false}] ``` The option also has a string shorthand: * `{"before": false, "after": true}` → `"after"` * `{"before": true, "after": false}` → `"before"` * `{"before": true, "after": true}` → `"both"` * `{"before": false, "after": false}` → `"neither"` ``` "yield-star-spacing": ["error", "after"] ``` Examples -------- ### after Examples of **correct** code for this rule with the default `"after"` option: ``` /\*eslint yield-star-spacing: ["error", "after"]\*/ /\*eslint-env es6\*/ function\* generator() { yield\* other(); } ``` ### before Examples of **correct** code for this rule with the `"before"` option: ``` /\*eslint yield-star-spacing: ["error", "before"]\*/ /\*eslint-env es6\*/ function \*generator() { yield \*other(); } ``` ### both Examples of **correct** code for this rule with the `"both"` option: ``` /\*eslint yield-star-spacing: ["error", "both"]\*/ /\*eslint-env es6\*/ function \* generator() { yield \* other(); } ``` ### neither Examples of **correct** code for this rule with the `"neither"` option: ``` /\*eslint yield-star-spacing: ["error", "neither"]\*/ /\*eslint-env es6\*/ function\*generator() { yield\*other(); } ``` When Not To Use It ------------------ If your project will not be using generators or you are not concerned with spacing consistency, you do not need this rule. Version ------- This rule was introduced in ESLint v2.0.0-alpha-1. Further Reading --------------- [Read Understanding ECMAScript 6 | Leanpub](https://leanpub.com/understandinges6/read/#leanpub-auto-generators) Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/yield-star-spacing.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/yield-star-spacing.js) eslint space-before-blocks space-before-blocks =================== Enforce consistent spacing before blocks 🔧 Fixable Some problems reported by this rule are automatically fixable by the `--fix` [command line](space-before-blocks../user-guide/command-line-interface#--fix) option Consistency is an important part of any style guide. While it is a personal preference where to put the opening brace of blocks, it should be consistent across a whole project. Having an inconsistent style distracts the reader from seeing the important parts of the code. Rule Details ------------ This rule will enforce consistency of spacing before blocks. It is only applied on blocks that don’t begin on a new line. * This rule ignores spacing which is between `=>` and a block. The spacing is handled by the `arrow-spacing` rule. * This rule ignores spacing which is between a keyword and a block. The spacing is handled by the `keyword-spacing` rule. * This rule ignores spacing which is between `:` of a switch case and a block. The spacing is handled by the `switch-colon-spacing` rule. Options ------- This rule takes one argument. If it is `"always"` then blocks must always have at least one preceding space. If `"never"` then all blocks should never have any preceding space. If different spacing is desired for function blocks, keyword blocks and classes, an optional configuration object can be passed as the rule argument to configure the cases separately. If any value in the configuration object is `"off"`, then neither style will be enforced for blocks of that kind. ( e.g. `{ "functions": "never", "keywords": "always", "classes": "always" }` ) The default is `"always"`. ### “always” Examples of **incorrect** code for this rule with the “always” option: ``` /\*eslint space-before-blocks: "error"\*/ if (a){ b(); } function a(){} for (;;){ b(); } try {} catch(a){} class Foo{ constructor(){} } ``` Examples of **correct** code for this rule with the `"always"` option: ``` /\*eslint space-before-blocks: "error"\*/ if (a) { b(); } if (a) { b(); } else{ /\*no error. this is checked by `keyword-spacing` rule.\*/ c(); } class C { static{} /\*no error. this is checked by `keyword-spacing` rule.\*/ } function a() {} for (;;) { b(); } try {} catch(a) {} ``` ### “never” Examples of **incorrect** code for this rule with the `"never"` option: ``` /\*eslint space-before-blocks: ["error", "never"]\*/ if (a) { b(); } function a() {} for (;;) { b(); } try {} catch(a) {} ``` Examples of **correct** code for this rule with the `"never"` option: ``` /\*eslint space-before-blocks: ["error", "never"]\*/ if (a){ b(); } function a(){} for (;;){ b(); } try{} catch(a){} class Foo{ constructor(){} } ``` Examples of **incorrect** code for this rule when configured `{ "functions": "never", "keywords": "always", "classes": "never" }`: ``` /\*eslint space-before-blocks: ["error", { "functions": "never", "keywords": "always", "classes": "never" }]\*/ /\*eslint-env es6\*/ function a() {} try {} catch(a){} class Foo{ constructor() {} } ``` Examples of **correct** code for this rule when configured `{ "functions": "never", "keywords": "always", "classes": "never" }`: ``` /\*eslint space-before-blocks: ["error", { "functions": "never", "keywords": "always", "classes": "never" }]\*/ /\*eslint-env es6\*/ for (;;) { // ... } describe(function(){ // ... }); class Foo{ constructor(){} } ``` Examples of **incorrect** code for this rule when configured `{ "functions": "always", "keywords": "never", "classes": "never" }`: ``` /\*eslint space-before-blocks: ["error", { "functions": "always", "keywords": "never", "classes": "never" }]\*/ /\*eslint-env es6\*/ function a(){} try {} catch(a) {} class Foo { constructor(){} } ``` Examples of **correct** code for this rule when configured `{ "functions": "always", "keywords": "never", "classes": "never" }`: ``` /\*eslint space-before-blocks: ["error", { "functions": "always", "keywords": "never", "classes": "never" }]\*/ /\*eslint-env es6\*/ if (a){ b(); } var a = function() {} class Foo{ constructor() {} } ``` Examples of **incorrect** code for this rule when configured `{ "functions": "never", "keywords": "never", "classes": "always" }`: ``` /\*eslint space-before-blocks: ["error", { "functions": "never", "keywords": "never", "classes": "always" }]\*/ /\*eslint-env es6\*/ class Foo{ constructor(){} } ``` Examples of **correct** code for this rule when configured `{ "functions": "never", "keywords": "never", "classes": "always" }`: ``` /\*eslint space-before-blocks: ["error", { "functions": "never", "keywords": "never", "classes": "always" }]\*/ /\*eslint-env es6\*/ class Foo { constructor(){} } ``` When Not To Use It ------------------ You can turn this rule off if you are not concerned with the consistency of spacing before blocks. Related Rules ------------- * <keyword-spacing> * <arrow-spacing> * <switch-colon-spacing> * <block-spacing> * <brace-style> Version ------- This rule was introduced in ESLint v0.9.0. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/space-before-blocks.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/space-before-blocks.js) eslint no-negated-condition no-negated-condition ==================== Disallow negated conditions Negated conditions are more difficult to understand. Code can be made more readable by inverting the condition instead. Rule Details ------------ This rule disallows negated conditions in either of the following: * `if` statements which have an `else` branch * ternary expressions Examples of **incorrect** code for this rule: ``` /\*eslint no-negated-condition: "error"\*/ if (!a) { doSomething(); } else { doSomethingElse(); } if (a != b) { doSomething(); } else { doSomethingElse(); } if (a !== b) { doSomething(); } else { doSomethingElse(); } !a ? c : b ``` Examples of **correct** code for this rule: ``` /\*eslint no-negated-condition: "error"\*/ if (!a) { doSomething(); } if (!a) { doSomething(); } else if (b) { doSomething(); } if (a != b) { doSomething(); } a ? b : c ``` Version ------- This rule was introduced in ESLint v1.6.0. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/no-negated-condition.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/no-negated-condition.js) eslint no-await-in-loop no-await-in-loop ================ Disallow `await` inside of loops Performing an operation on each element of an iterable is a common task. However, performing an `await` as part of each operation is an indication that the program is not taking full advantage of the parallelization benefits of `async`/`await`. Usually, the code should be refactored to create all the promises at once, then get access to the results using `Promise.all()`. Otherwise, each successive operation will not start until the previous one has completed. Concretely, the following function should be refactored as shown: ``` async function foo(things) { const results = []; for (const thing of things) { // Bad: each loop iteration is delayed until the entire asynchronous operation completes results.push(await bar(thing)); } return baz(results); } ``` ``` async function foo(things) { const results = []; for (const thing of things) { // Good: all asynchronous operations are immediately started. results.push(bar(thing)); } // Now that all the asynchronous operations are running, here we wait until they all complete. return baz(await Promise.all(results)); } ``` Rule Details ------------ This rule disallows the use of `await` within loop bodies. Examples -------- Examples of **correct** code for this rule: ``` /\*eslint no-await-in-loop: "error"\*/ async function foo(things) { const results = []; for (const thing of things) { // Good: all asynchronous operations are immediately started. results.push(bar(thing)); } // Now that all the asynchronous operations are running, here we wait until they all complete. return baz(await Promise.all(results)); } ``` Examples of **incorrect** code for this rule: ``` /\*eslint no-await-in-loop: "error"\*/ async function foo(things) { const results = []; for (const thing of things) { // Bad: each loop iteration is delayed until the entire asynchronous operation completes results.push(await bar(thing)); } return baz(results); } ``` When Not To Use It ------------------ In many cases the iterations of a loop are not actually independent of each-other. For example, the output of one iteration might be used as the input to another. Or, loops may be used to retry asynchronous operations that were unsuccessful. Or, loops may be used to prevent your code from sending an excessive amount of requests in parallel. In such cases it makes sense to use `await` within a loop and it is recommended to disable the rule via a standard ESLint disable comment. Version ------- This rule was introduced in ESLint v3.12.0. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/no-await-in-loop.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/no-await-in-loop.js) eslint use-isnan use-isnan ========= Require calls to `isNaN()` when checking for `NaN` ✅ Recommended The `"extends": "eslint:recommended"` property in a [configuration file](use-isnan../user-guide/configuring/configuration-files#extending-configuration-files) enables this rule In JavaScript, `NaN` is a special value of the `Number` type. It’s used to represent any of the “not-a-number” values represented by the double-precision 64-bit format as specified by the IEEE Standard for Binary Floating-Point Arithmetic. Because `NaN` is unique in JavaScript by not being equal to anything, including itself, the results of comparisons to `NaN` are confusing: * `NaN === NaN` or `NaN == NaN` evaluate to false * `NaN !== NaN` or `NaN != NaN` evaluate to true Therefore, use `Number.isNaN()` or global `isNaN()` functions to test whether a value is `NaN`. Rule Details ------------ This rule disallows comparisons to ‘NaN’. Examples of **incorrect** code for this rule: ``` /\*eslint use-isnan: "error"\*/ if (foo == NaN) { // ... } if (foo != NaN) { // ... } if (foo == Number.NaN) { // ... } if (foo != Number.NaN) { // ... } ``` Examples of **correct** code for this rule: ``` /\*eslint use-isnan: "error"\*/ if (isNaN(foo)) { // ... } if (!isNaN(foo)) { // ... } ``` Options ------- This rule has an object option, with two options: * `"enforceForSwitchCase": true` (default) additionally disallows `case NaN` and `switch(NaN)` in `switch` statements. * `"enforceForIndexOf": true` additionally disallows the use of `indexOf` and `lastIndexOf` methods with `NaN`. Default is `false`, meaning that this rule by default does not warn about `indexOf(NaN)` or `lastIndexOf(NaN)` method calls. ### enforceForSwitchCase The `switch` statement internally uses the `===` comparison to match the expression’s value to a case clause. Therefore, it can never match `case NaN`. Also, `switch(NaN)` can never match a case clause. Examples of **incorrect** code for this rule with `"enforceForSwitchCase"` option set to `true` (default): ``` /\*eslint use-isnan: ["error", {"enforceForSwitchCase": true}]\*/ switch (foo) { case NaN: bar(); break; case 1: baz(); break; // ... } switch (NaN) { case a: bar(); break; case b: baz(); break; // ... } switch (foo) { case Number.NaN: bar(); break; case 1: baz(); break; // ... } switch (Number.NaN) { case a: bar(); break; case b: baz(); break; // ... } ``` Examples of **correct** code for this rule with `"enforceForSwitchCase"` option set to `true` (default): ``` /\*eslint use-isnan: ["error", {"enforceForSwitchCase": true}]\*/ if (Number.isNaN(foo)) { bar(); } else { switch (foo) { case 1: baz(); break; // ... } } if (Number.isNaN(a)) { bar(); } else if (Number.isNaN(b)) { baz(); } // ... ``` Examples of **correct** code for this rule with `"enforceForSwitchCase"` option set to `false`: ``` /\*eslint use-isnan: ["error", {"enforceForSwitchCase": false}]\*/ switch (foo) { case NaN: bar(); break; case 1: baz(); break; // ... } switch (NaN) { case a: bar(); break; case b: baz(); break; // ... } switch (foo) { case Number.NaN: bar(); break; case 1: baz(); break; // ... } switch (Number.NaN) { case a: bar(); break; case b: baz(); break; // ... } ``` ### enforceForIndexOf The following methods internally use the `===` comparison to match the given value with an array element: * [`Array.prototype.indexOf`](https://www.ecma-international.org/ecma-262/6.0/#sec-array.prototype.indexof) * [`Array.prototype.lastIndexOf`](https://www.ecma-international.org/ecma-262/6.0/#sec-array.prototype.lastindexof) Therefore, for any array `foo`, `foo.indexOf(NaN)` and `foo.lastIndexOf(NaN)` will always return `-1`. Set `"enforceForIndexOf"` to `true` if you want this rule to report `indexOf(NaN)` and `lastIndexOf(NaN)` method calls. Examples of **incorrect** code for this rule with `"enforceForIndexOf"` option set to `true`: ``` /\*eslint use-isnan: ["error", {"enforceForIndexOf": true}]\*/ var hasNaN = myArray.indexOf(NaN) >= 0; var firstIndex = myArray.indexOf(NaN); var lastIndex = myArray.lastIndexOf(NaN); ``` Examples of **correct** code for this rule with `"enforceForIndexOf"` option set to `true`: ``` /\*eslint use-isnan: ["error", {"enforceForIndexOf": true}]\*/ function myIsNaN(val) { return typeof val === "number" && isNaN(val); } function indexOfNaN(arr) { for (var i = 0; i < arr.length; i++) { if (myIsNaN(arr[i])) { return i; } } return -1; } function lastIndexOfNaN(arr) { for (var i = arr.length - 1; i >= 0; i--) { if (myIsNaN(arr[i])) { return i; } } return -1; } var hasNaN = myArray.some(myIsNaN); var hasNaN = indexOfNaN(myArray) >= 0; var firstIndex = indexOfNaN(myArray); var lastIndex = lastIndexOfNaN(myArray); // ES2015 var hasNaN = myArray.some(Number.isNaN); // ES2015 var firstIndex = myArray.findIndex(Number.isNaN); // ES2016 var hasNaN = myArray.includes(NaN); ``` #### Known Limitations This option checks methods with the given names, *even if* the object which has the method is *not* an array. Version ------- This rule was introduced in ESLint v0.0.6. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/use-isnan.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/use-isnan.js)
programming_docs
eslint consistent-this consistent-this =============== Enforce consistent naming when capturing the current execution context It is often necessary to capture the current execution context in order to make it available subsequently. A prominent example of this are jQuery callbacks: ``` var that = this; jQuery('li').click(function (event) { // here, "this" is the HTMLElement where the click event occurred that.setFoo(42); }); ``` There are many commonly used aliases for `this` such as `that`, `self` or `me`. It is desirable to ensure that whichever alias the team agrees upon is used consistently throughout the application. Rule Details ------------ This rule enforces two things about variables with the designated alias names for `this`: * If a variable with a designated name is declared, it *must* be either initialized (in the declaration) or assigned (in the same scope as the declaration) the value `this`. * If a variable is initialized or assigned the value `this`, the name of the variable *must* be a designated alias. Options ------- This rule has one or more string options: * designated alias names for `this` (default `"that"`) Examples of **incorrect** code for this rule with the default `"that"` option: ``` /\*eslint consistent-this: ["error", "that"]\*/ var that = 42; var self = this; that = 42; self = this; ``` Examples of **correct** code for this rule with the default `"that"` option: ``` /\*eslint consistent-this: ["error", "that"]\*/ var that = this; var self = 42; var self; that = this; foo.bar = this; ``` Examples of **incorrect** code for this rule with the default `"that"` option, if the variable is not initialized: ``` /\*eslint consistent-this: ["error", "that"]\*/ var that; function f() { that = this; } ``` Examples of **correct** code for this rule with the default `"that"` option, if the variable is not initialized: ``` /\*eslint consistent-this: ["error", "that"]\*/ var that; that = this; var foo, that; foo = 42; that = this; ``` When Not To Use It ------------------ If you need to capture nested context, `consistent-this` is going to be problematic. Code of that nature is usually difficult to read and maintain and you should consider refactoring it. Version ------- This rule was introduced in ESLint v0.0.9. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/consistent-this.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/consistent-this.js) eslint no-obj-calls no-obj-calls ============ Disallow calling global object properties as functions ✅ Recommended The `"extends": "eslint:recommended"` property in a [configuration file](no-obj-calls../user-guide/configuring/configuration-files#extending-configuration-files) enables this rule ECMAScript provides several global objects that are intended to be used as-is. Some of these objects look as if they could be constructors due their capitalization (such as `Math` and `JSON`) but will throw an error if you try to execute them as functions. The [ECMAScript 5 specification](https://es5.github.io/#x15.8) makes it clear that both `Math` and `JSON` cannot be invoked: > The Math object does not have a `[[Call]]` internal property; it is not possible to invoke the Math object as a function. > > The [ECMAScript 2015 specification](https://www.ecma-international.org/ecma-262/6.0/index.html#sec-reflect-object) makes it clear that `Reflect` cannot be invoked: > The Reflect object also does not have a `[[Call]]` internal method; it is not possible to invoke the Reflect object as a function. > > The [ECMAScript 2017 specification](https://www.ecma-international.org/ecma-262/8.0/index.html#sec-atomics-object) makes it clear that `Atomics` cannot be invoked: > The Atomics object does not have a `[[Call]]` internal method; it is not possible to invoke the Atomics object as a function. > > And the [ECMAScript Internationalization API Specification](https://tc39.es/ecma402/#intl-object) makes it clear that `Intl` cannot be invoked: > The Intl object does not have a `[[Call]]` internal method; it is not possible to invoke the Intl object as a function. > > Rule Details ------------ This rule disallows calling the `Math`, `JSON`, `Reflect`, `Atomics` and `Intl` objects as functions. This rule also disallows using these objects as constructors with the `new` operator. Examples of **incorrect** code for this rule: ``` /\*eslint no-obj-calls: "error"\*/ /\*eslint-env es2017, browser \*/ var math = Math(); var newMath = new Math(); var json = JSON(); var newJSON = new JSON(); var reflect = Reflect(); var newReflect = new Reflect(); var atomics = Atomics(); var newAtomics = new Atomics(); var intl = Intl(); var newIntl = new Intl(); ``` Examples of **correct** code for this rule: ``` /\*eslint no-obj-calls: "error"\*/ /\*eslint-env es2017, browser\*/ function area(r) { return Math.PI \* r \* r; } var object = JSON.parse("{}"); var value = Reflect.get({ x: 1, y: 2 }, "x"); var first = Atomics.load(foo, 0); var segmenterFr = new Intl.Segmenter("fr", { granularity: "word" }); ``` Version ------- This rule was introduced in ESLint v0.0.9. Further Reading --------------- [Annotated ES5](https://es5.github.io/#x15.8) Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/no-obj-calls.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/no-obj-calls.js) eslint wrap-iife wrap-iife ========= Require parentheses around immediate `function` invocations 🔧 Fixable Some problems reported by this rule are automatically fixable by the `--fix` [command line](wrap-iife../user-guide/command-line-interface#--fix) option You can immediately invoke function expressions, but not function declarations. A common technique to create an immediately-invoked function expression (IIFE) is to wrap a function declaration in parentheses. The opening parentheses causes the contained function to be parsed as an expression, rather than a declaration. ``` // function expression could be unwrapped var x = function () { return { y: 1 };}(); // function declaration must be wrapped function () { /\* side effects \*/ }(); // SyntaxError ``` Rule Details ------------ This rule requires all immediately-invoked function expressions to be wrapped in parentheses. Options ------- This rule has two options, a string option and an object option. String option: * `"outside"` enforces always wrapping the *call* expression. The default is `"outside"`. * `"inside"` enforces always wrapping the *function* expression. * `"any"` enforces always wrapping, but allows either style. Object option: * `"functionPrototypeMethods": true` additionally enforces wrapping function expressions invoked using `.call` and `.apply`. The default is `false`. ### outside Examples of **incorrect** code for the default `"outside"` option: ``` /\*eslint wrap-iife: ["error", "outside"]\*/ var x = function () { return { y: 1 };}(); // unwrapped var x = (function () { return { y: 1 };})(); // wrapped function expression ``` Examples of **correct** code for the default `"outside"` option: ``` /\*eslint wrap-iife: ["error", "outside"]\*/ var x = (function () { return { y: 1 };}()); // wrapped call expression ``` ### inside Examples of **incorrect** code for the `"inside"` option: ``` /\*eslint wrap-iife: ["error", "inside"]\*/ var x = function () { return { y: 1 };}(); // unwrapped var x = (function () { return { y: 1 };}()); // wrapped call expression ``` Examples of **correct** code for the `"inside"` option: ``` /\*eslint wrap-iife: ["error", "inside"]\*/ var x = (function () { return { y: 1 };})(); // wrapped function expression ``` ### any Examples of **incorrect** code for the `"any"` option: ``` /\*eslint wrap-iife: ["error", "any"]\*/ var x = function () { return { y: 1 };}(); // unwrapped ``` Examples of **correct** code for the `"any"` option: ``` /\*eslint wrap-iife: ["error", "any"]\*/ var x = (function () { return { y: 1 };}()); // wrapped call expression var x = (function () { return { y: 1 };})(); // wrapped function expression ``` ### functionPrototypeMethods Examples of **incorrect** code for this rule with the `"inside", { "functionPrototypeMethods": true }` options: ``` /\* eslint wrap-iife: [2, "inside", { functionPrototypeMethods: true }] \*/ var x = function(){ foo(); }() var x = (function(){ foo(); }()) var x = function(){ foo(); }.call(bar) var x = (function(){ foo(); }.call(bar)) ``` Examples of **correct** code for this rule with the `"inside", { "functionPrototypeMethods": true }` options: ``` /\* eslint wrap-iife: [2, "inside", { functionPrototypeMethods: true }] \*/ var x = (function(){ foo(); })() var x = (function(){ foo(); }).call(bar) ``` Version ------- This rule was introduced in ESLint v0.0.9. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/wrap-iife.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/wrap-iife.js) eslint no-useless-rename no-useless-rename ================= Disallow renaming import, export, and destructured assignments to the same name 🔧 Fixable Some problems reported by this rule are automatically fixable by the `--fix` [command line](no-useless-rename../user-guide/command-line-interface#--fix) option ES2015 allows for the renaming of references in import and export statements as well as destructuring assignments. This gives programmers a concise syntax for performing these operations while renaming these references: ``` import { foo as bar } from "baz"; export { foo as bar }; let { foo: bar } = baz; ``` With this syntax, it is possible to rename a reference to the same name. This is a completely redundant operation, as this is the same as not renaming at all. For example, this: ``` import { foo as foo } from "bar"; export { foo as foo }; let { foo: foo } = bar; ``` is the same as: ``` import { foo } from "bar"; export { foo }; let { foo } = bar; ``` Rule Details ------------ This rule disallows the renaming of import, export, and destructured assignments to the same name. Options ------- This rule allows for more fine-grained control with the following options: * `ignoreImport`: When set to `true`, this rule does not check imports * `ignoreExport`: When set to `true`, this rule does not check exports * `ignoreDestructuring`: When set to `true`, this rule does not check destructuring assignments By default, all options are set to `false`: ``` "no-useless-rename": ["error", { "ignoreDestructuring": false, "ignoreImport": false, "ignoreExport": false }] ``` Examples of **incorrect** code for this rule by default: ``` /\*eslint no-useless-rename: "error"\*/ import { foo as foo } from "bar"; import { "foo" as foo } from "bar"; export { foo as foo }; export { foo as "foo" }; export { foo as foo } from "bar"; export { "foo" as "foo" } from "bar"; let { foo: foo } = bar; let { 'foo': foo } = bar; function foo({ bar: bar }) {} ({ foo: foo }) => {} ``` Examples of **correct** code for this rule by default: ``` /\*eslint no-useless-rename: "error"\*/ import \* as foo from "foo"; import { foo } from "bar"; import { foo as bar } from "baz"; import { "foo" as bar } from "baz"; export { foo }; export { foo as bar }; export { foo as "bar" }; export { foo as bar } from "foo"; export { "foo" as "bar" } from "foo"; let { foo } = bar; let { foo: bar } = baz; let { [foo]: foo } = bar; function foo({ bar }) {} function foo({ bar: baz }) {} ({ foo }) => {} ({ foo: bar }) => {} ``` Examples of **correct** code for this rule with `{ ignoreImport: true }`: ``` /\*eslint no-useless-rename: ["error", { ignoreImport: true }]\*/ import { foo as foo } from "bar"; ``` Examples of **correct** code for this rule with `{ ignoreExport: true }`: ``` /\*eslint no-useless-rename: ["error", { ignoreExport: true }]\*/ export { foo as foo }; export { foo as foo } from "bar"; ``` Examples of **correct** code for this rule with `{ ignoreDestructuring: true }`: ``` /\*eslint no-useless-rename: ["error", { ignoreDestructuring: true }]\*/ let { foo: foo } = bar; function foo({ bar: bar }) {} ({ foo: foo }) => {} ``` When Not To Use It ------------------ You can safely disable this rule if you do not care about redundantly renaming import, export, and destructuring assignments. Compatibility ------------- * **JSCS**: [disallowIdenticalDestructuringNames](https://jscs-dev.github.io/rule/disallowIdenticalDestructuringNames) Related Rules ------------- * <object-shorthand> Version ------- This rule was introduced in ESLint v2.11.0. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/no-useless-rename.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/no-useless-rename.js) eslint no-compare-neg-zero no-compare-neg-zero =================== Disallow comparing against -0 ✅ Recommended The `"extends": "eslint:recommended"` property in a [configuration file](no-compare-neg-zero../user-guide/configuring/configuration-files#extending-configuration-files) enables this rule Rule Details ------------ The rule should warn against code that tries to compare against `-0`, since that will not work as intended. That is, code like `x === -0` will pass for both `+0` and `-0`. The author probably intended `Object.is(x, -0)`. Examples of **incorrect** code for this rule: ``` /\* eslint no-compare-neg-zero: "error" \*/ if (x === -0) { // doSomething()... } ``` Examples of **correct** code for this rule: ``` /\* eslint no-compare-neg-zero: "error" \*/ if (x === 0) { // doSomething()... } ``` ``` /\* eslint no-compare-neg-zero: "error" \*/ if (Object.is(x, -0)) { // doSomething()... } ``` Version ------- This rule was introduced in ESLint v3.17.0. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/no-compare-neg-zero.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/no-compare-neg-zero.js) eslint no-irregular-whitespace no-irregular-whitespace ======================= Disallow irregular whitespace ✅ Recommended The `"extends": "eslint:recommended"` property in a [configuration file](no-irregular-whitespace../user-guide/configuring/configuration-files#extending-configuration-files) enables this rule Invalid or irregular whitespace causes issues with ECMAScript 5 parsers and also makes code harder to debug in a similar nature to mixed tabs and spaces. Various whitespace characters can be inputted by programmers by mistake for example from copying or keyboard shortcuts. Pressing Alt + Space on macOS adds in a non breaking space character for example. A simple fix for this problem could be to rewrite the offending line from scratch. This might also be a problem introduced by the text editor: if rewriting the line does not fix it, try using a different editor. Known issues these spaces cause: * Zero Width Space + Is NOT considered a separator for tokens and is often parsed as an `Unexpected token ILLEGAL` + Is NOT shown in modern browsers making code repository software expected to resolve the visualization * Line Separator + Is NOT a valid character within JSON which would cause parse errors Rule Details ------------ This rule is aimed at catching invalid whitespace that is not a normal tab and space. Some of these characters may cause issues in modern browsers and others will be a debugging issue to spot. This rule disallows the following characters except where the options allow: ``` \u000B - Line Tabulation (\v) - <VT> \u000C - Form Feed (\f) - <FF> \u00A0 - No-Break Space - <NBSP> \u0085 - Next Line \u1680 - Ogham Space Mark \u180E - Mongolian Vowel Separator - <MVS> \ufeff - Zero Width No-Break Space - <BOM> \u2000 - En Quad \u2001 - Em Quad \u2002 - En Space - <ENSP> \u2003 - Em Space - <EMSP> \u2004 - Three-Per-Em \u2005 - Four-Per-Em \u2006 - Six-Per-Em \u2007 - Figure Space \u2008 - Punctuation Space - <PUNCSP> \u2009 - Thin Space \u200A - Hair Space \u200B - Zero Width Space - <ZWSP> \u2028 - Line Separator \u2029 - Paragraph Separator \u202F - Narrow No-Break Space \u205f - Medium Mathematical Space \u3000 - Ideographic Space ``` Options ------- This rule has an object option for exceptions: * `"skipStrings": true` (default) allows any whitespace characters in string literals * `"skipComments": true` allows any whitespace characters in comments * `"skipRegExps": true` allows any whitespace characters in regular expression literals * `"skipTemplates": true` allows any whitespace characters in template literals ### skipStrings Examples of **incorrect** code for this rule with the default `{ "skipStrings": true }` option: ``` /\*eslint no-irregular-whitespace: "error"\*/ function thing() /\*<NBSP>\*/{ return 'test'; } function thing( /\*<NBSP>\*/){ return 'test'; } function thing /\*<NBSP>\*/(){ return 'test'; } function thing᠎/\*<MVS>\*/(){ return 'test'; } function thing() { return 'test'; /\*<ENSP>\*/ } function thing() { return 'test'; /\*<NBSP>\*/ } function thing() { // Description <NBSP>: some descriptive text } /\* Description <NBSP>: some descriptive text \*/ function thing() { return / <NBSP>regexp/; } /\*eslint-env es6\*/ function thing() { return `template <NBSP>string`; } ``` Examples of **correct** code for this rule with the default `{ "skipStrings": true }` option: ``` /\*eslint no-irregular-whitespace: "error"\*/ function thing() { return ' <NBSP>thing'; } function thing() { return '​<ZWSP>thing'; } function thing() { return 'th <NBSP>ing'; } ``` ### skipComments Examples of additional **correct** code for this rule with the `{ "skipComments": true }` option: ``` /\*eslint no-irregular-whitespace: ["error", { "skipComments": true }]\*/ function thing() { // Description <NBSP>: some descriptive text } /\* Description <NBSP>: some descriptive text \*/ ``` ### skipRegExps Examples of additional **correct** code for this rule with the `{ "skipRegExps": true }` option: ``` /\*eslint no-irregular-whitespace: ["error", { "skipRegExps": true }]\*/ function thing() { return / <NBSP>regexp/; } ``` ### skipTemplates Examples of additional **correct** code for this rule with the `{ "skipTemplates": true }` option: ``` /\*eslint no-irregular-whitespace: ["error", { "skipTemplates": true }]\*/ /\*eslint-env es6\*/ function thing() { return `template <NBSP>string`; } ``` When Not To Use It ------------------ If you decide that you wish to use whitespace other than tabs and spaces outside of strings in your application. Version ------- This rule was introduced in ESLint v0.9.0. Further Reading --------------- [Annotated ES5](https://es5.github.io/#x7.2) [JSON: The JavaScript subset that isn’t - Timeless](https://web.archive.org/web/20200414142829/http://timelessrepo.com/json-isnt-a-javascript-subset) Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/no-irregular-whitespace.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/no-irregular-whitespace.js) eslint no-dupe-else-if no-dupe-else-if =============== Disallow duplicate conditions in if-else-if chains ✅ Recommended The `"extends": "eslint:recommended"` property in a [configuration file](no-dupe-else-if../user-guide/configuring/configuration-files#extending-configuration-files) enables this rule `if-else-if` chains are commonly used when there is a need to execute only one branch (or at most one branch) out of several possible branches, based on certain conditions. ``` if (a) { foo(); } else if (b) { bar(); } else if (c) { baz(); } ``` Two identical test conditions in the same chain are almost always a mistake in the code. Unless there are side effects in the expressions, a duplicate will evaluate to the same `true` or `false` value as the identical expression earlier in the chain, meaning that its branch can never execute. ``` if (a) { foo(); } else if (b) { bar(); } else if (b) { baz(); } ``` In the above example, `baz()` can never execute. Obviously, `baz()` could be executed only when `b` evaluates to `true`, but in that case `bar()` would be executed instead, since it’s earlier in the chain. Rule Details ------------ This rule disallows duplicate conditions in the same `if-else-if` chain. Examples of **incorrect** code for this rule: ``` /\*eslint no-dupe-else-if: "error"\*/ if (isSomething(x)) { foo(); } else if (isSomething(x)) { bar(); } if (a) { foo(); } else if (b) { bar(); } else if (c && d) { baz(); } else if (c && d) { quux(); } else { quuux(); } if (n === 1) { foo(); } else if (n === 2) { bar(); } else if (n === 3) { baz(); } else if (n === 2) { quux(); } else if (n === 5) { quuux(); } ``` Examples of **correct** code for this rule: ``` /\*eslint no-dupe-else-if: "error"\*/ if (isSomething(x)) { foo(); } else if (isSomethingElse(x)) { bar(); } if (a) { foo(); } else if (b) { bar(); } else if (c && d) { baz(); } else if (c && e) { quux(); } else { quuux(); } if (n === 1) { foo(); } else if (n === 2) { bar(); } else if (n === 3) { baz(); } else if (n === 4) { quux(); } else if (n === 5) { quuux(); } ``` This rule can also detect some cases where the conditions are not identical, but the branch can never execute due to the logic of `||` and `&&` operators. Examples of additional **incorrect** code for this rule: ``` /\*eslint no-dupe-else-if: "error"\*/ if (a || b) { foo(); } else if (a) { bar(); } if (a) { foo(); } else if (b) { bar(); } else if (a || b) { baz(); } if (a) { foo(); } else if (a && b) { bar(); } if (a && b) { foo(); } else if (a && b && c) { bar(); } if (a || b) { foo(); } else if (b && c) { bar(); } if (a) { foo(); } else if (b && c) { bar(); } else if (d && (c && e && b || a)) { baz(); } ``` Please note that this rule does not compare conditions from the chain with conditions inside statements, and will not warn in the cases such as follows: ``` if (a) { if (a) { foo(); } } if (a) { foo(); } else { if (a) { bar(); } } ``` When Not To Use It ------------------ In rare cases where you really need identical test conditions in the same chain, which necessarily means that the expressions in the chain are causing and relying on side effects, you will have to turn this rule off. Related Rules ------------- * <no-duplicate-case> * <no-lonely-if> Version ------- This rule was introduced in ESLint v6.7.0. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/no-dupe-else-if.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/no-dupe-else-if.js)
programming_docs
eslint no-extend-native no-extend-native ================ Disallow extending native types In JavaScript, you can extend any object, including builtin or “native” objects. Sometimes people change the behavior of these native objects in ways that break the assumptions made about them in other parts of the code. For example here we are overriding a builtin method that will then affect all Objects, even other builtins. ``` // seems harmless Object.prototype.extra = 55; // loop through some userIds var users = { "123": "Stan", "456": "David" }; // not what you'd expect for (var id in users) { console.log(id); // "123", "456", "extra" } ``` A common suggestion to avoid this problem would be to wrap the inside of the `for` loop with `users.hasOwnProperty(id)`. However, if this rule is strictly enforced throughout your codebase you won’t need to take that step. Rule Details ------------ Disallows directly modifying the prototype of builtin objects. Examples of **incorrect** code for this rule: ``` /\*eslint no-extend-native: "error"\*/ Object.prototype.a = "a"; Object.defineProperty(Array.prototype, "times", { value: 999 }); ``` Options ------- This rule accepts an `exceptions` option, which can be used to specify a list of builtins for which extensions will be allowed. ### exceptions Examples of **correct** code for the sample `{ "exceptions": ["Object"] }` option: ``` /\*eslint no-extend-native: ["error", { "exceptions": ["Object"] }]\*/ Object.prototype.a = "a"; ``` Known Limitations ----------------- This rule *does not* report any of the following less obvious approaches to modify the prototype of builtin objects: ``` var x = Object; x.prototype.thing = a; eval("Array.prototype.forEach = 'muhahaha'"); with(Array) { prototype.thing = 'thing'; }; window.Function.prototype.bind = 'tight'; ``` When Not To Use It ------------------ You may want to disable this rule when working with polyfills that try to patch older versions of JavaScript with the latest spec, such as those that might `Function.prototype.bind` or `Array.prototype.forEach` in a future-friendly way. Related Rules ------------- * <no-global-assign> Version ------- This rule was introduced in ESLint v0.1.4. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/no-extend-native.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/no-extend-native.js) eslint require-await require-await ============= Disallow async functions which have no `await` expression Asynchronous functions in JavaScript behave differently than other functions in two important ways: 1. The return value is always a `Promise`. 2. You can use the `await` operator inside of them. The primary reason to use asynchronous functions is typically to use the `await` operator, such as this: ``` async function fetchData(processDataItem) { const response = await fetch(DATA\_URL); const data = await response.json(); return data.map(processDataItem); } ``` Asynchronous functions that don’t use `await` might not need to be asynchronous functions and could be the unintentional result of refactoring. Note: this rule ignores async generator functions. This is because generators yield rather than return a value and async generators might yield all the values of another async generator without ever actually needing to use await. Rule Details ------------ This rule warns async functions which have no `await` expression. Examples of **incorrect** code for this rule: ``` /\*eslint require-await: "error"\*/ async function foo() { doSomething(); } bar(async () => { doSomething(); }); ``` Examples of **correct** code for this rule: ``` /\*eslint require-await: "error"\*/ async function foo() { await doSomething(); } bar(async () => { await doSomething(); }); function foo() { doSomething(); } bar(() => { doSomething(); }); // Allow empty functions. async function noop() {} ``` When Not To Use It ------------------ Asynchronous functions are designed to work with promises such that throwing an error will cause a promise’s rejection handler (such as `catch()`) to be called. For example: ``` async function fail() { throw new Error("Failure!"); } fail().catch(error => { console.log(error.message); }); ``` In this case, the `fail()` function throws an error that is intended to be caught by the `catch()` handler assigned later. Converting the `fail()` function into a synchronous function would require the call to `fail()` to be refactored to use a `try-catch` statement instead of a promise. If you are throwing an error inside of an asynchronous function for this purpose, then you may want to disable this rule. Related Rules ------------- * <require-yield> Version ------- This rule was introduced in ESLint v3.11.0. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/require-await.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/require-await.js) eslint object-curly-newline object-curly-newline ==================== Enforce consistent line breaks after opening and before closing braces 🔧 Fixable Some problems reported by this rule are automatically fixable by the `--fix` [command line](object-curly-newline../user-guide/command-line-interface#--fix) option A number of style guides require or disallow line breaks inside of object braces and other tokens. Rule Details ------------ This rule requires or disallows a line break between `{` and its following token, and between `}` and its preceding token of object literals or destructuring assignments. Options ------- This rule has either a string option: * `"always"` requires line breaks after opening and before closing braces * `"never"` disallows line breaks after opening and before closing braces Or an object option: * `"multiline": true` requires line breaks if there are line breaks inside properties or between properties. Otherwise, it disallows line breaks. * `"minProperties"` requires line breaks if the number of properties is at least the given integer. By default, an error will also be reported if an object contains linebreaks and has fewer properties than the given integer. However, the second behavior is disabled if the `consistent` option is set to `true` * `"consistent": true` (default) requires that either both curly braces, or neither, directly enclose newlines. Note that enabling this option will also change the behavior of the `minProperties` option. (See `minProperties` above for more information) You can specify different options for object literals, destructuring assignments, and named imports and exports: ``` { "object-curly-newline": ["error", { "ObjectExpression": "always", "ObjectPattern": { "multiline": true }, "ImportDeclaration": "never", "ExportDeclaration": { "multiline": true, "minProperties": 3 } }] } ``` * `"ObjectExpression"` configuration for object literals * `"ObjectPattern"` configuration for object patterns of destructuring assignments * `"ImportDeclaration"` configuration for named imports * `"ExportDeclaration"` configuration for named exports ### always Examples of **incorrect** code for this rule with the `"always"` option: ``` /\*eslint object-curly-newline: ["error", "always"]\*/ /\*eslint-env es6\*/ let a = {}; let b = {foo: 1}; let c = {foo: 1, bar: 2}; let d = {foo: 1, bar: 2}; let e = {foo() { dosomething(); }}; let {} = obj; let {f} = obj; let {g, h} = obj; let {i, j} = obj; let {k = function() { dosomething(); }} = obj; ``` Examples of **correct** code for this rule with the `"always"` option: ``` /\*eslint object-curly-newline: ["error", "always"]\*/ /\*eslint-env es6\*/ let a = { }; let b = { foo: 1 }; let c = { foo: 1, bar: 2 }; let d = { foo: 1, bar: 2 }; let e = { foo: function() { dosomething(); } }; let { } = obj; let { f } = obj; let { g, h } = obj; let { i, j } = obj; let { k = function() { dosomething(); } } = obj; ``` ### never Examples of **incorrect** code for this rule with the `"never"` option: ``` /\*eslint object-curly-newline: ["error", "never"]\*/ /\*eslint-env es6\*/ let a = { }; let b = { foo: 1 }; let c = { foo: 1, bar: 2 }; let d = { foo: 1, bar: 2 }; let e = { foo: function() { dosomething(); } }; let { } = obj; let { f } = obj; let { g, h } = obj; let { i, j } = obj; let { k = function() { dosomething(); } } = obj; ``` Examples of **correct** code for this rule with the `"never"` option: ``` /\*eslint object-curly-newline: ["error", "never"]\*/ /\*eslint-env es6\*/ let a = {}; let b = {foo: 1}; let c = {foo: 1, bar: 2}; let d = {foo: 1, bar: 2}; let e = {foo: function() { dosomething(); }}; let {} = obj; let {f} = obj; let {g, h} = obj; let {i, j} = obj; let {k = function() { dosomething(); }} = obj; ``` ### multiline Examples of **incorrect** code for this rule with the `{ "multiline": true }` option: ``` /\*eslint object-curly-newline: ["error", { "multiline": true }]\*/ /\*eslint-env es6\*/ let a = { }; let b = { foo: 1 }; let c = { foo: 1, bar: 2 }; let d = {foo: 1, bar: 2}; let e = {foo: function() { dosomething(); }}; let { } = obj; let { f } = obj; let { g, h } = obj; let {i, j} = obj; let {k = function() { dosomething(); }} = obj; ``` Examples of **correct** code for this rule with the `{ "multiline": true }` option: ``` /\*eslint object-curly-newline: ["error", { "multiline": true }]\*/ /\*eslint-env es6\*/ let a = {}; let b = {foo: 1}; let c = {foo: 1, bar: 2}; let d = { foo: 1, bar: 2 }; let e = { foo: function() { dosomething(); } }; let {} = obj; let {f} = obj; let {g, h} = obj; let { i, j } = obj; let { k = function() { dosomething(); } } = obj; ``` ### minProperties Examples of **incorrect** code for this rule with the `{ "minProperties": 2 }` option: ``` /\*eslint object-curly-newline: ["error", { "minProperties": 2 }]\*/ /\*eslint-env es6\*/ let a = { }; let b = { foo: 1 }; let c = {foo: 1, bar: 2}; let d = {foo: 1, bar: 2}; let e = { foo: function() { dosomething(); } }; let { } = obj; let { f } = obj; let {g, h} = obj; let {i, j} = obj; let { k = function() { dosomething(); } } = obj; ``` Examples of **correct** code for this rule with the `{ "minProperties": 2 }` option: ``` /\*eslint object-curly-newline: ["error", { "minProperties": 2 }]\*/ /\*eslint-env es6\*/ let a = {}; let b = {foo: 1}; let c = { foo: 1, bar: 2 }; let d = { foo: 1, bar: 2 }; let e = {foo: function() { dosomething(); }}; let {} = obj; let {f} = obj; let { g, h } = obj; let { i, j } = obj; let {k = function() { dosomething(); }} = obj; ``` ### consistent Examples of **incorrect** code for this rule with the default `{ "consistent": true }` option: ``` /\*eslint object-curly-newline: ["error", { "consistent": true }]\*/ /\*eslint-env es6\*/ let a = {foo: 1 }; let b = { foo: 1}; let c = {foo: 1, bar: 2 }; let d = { foo: 1, bar: 2}; let e = {foo: function() { dosomething(); } }; let f = { foo: function() { dosomething();}}; let {g } = obj; let { h} = obj; let {i, j } = obj; let {k, l } = obj; let { m, n} = obj; let { o, p} = obj; let {q = function() { dosomething(); } } = obj; let { r = function() { dosomething(); }} = obj; ``` Examples of **correct** code for this rule with the default `{ "consistent": true }` option: ``` /\*eslint object-curly-newline: ["error", { "consistent": true }]\*/ /\*eslint-env es6\*/ let empty1 = {}; let empty2 = { }; let a = {foo: 1}; let b = { foo: 1 }; let c = { foo: 1, bar: 2 }; let d = { foo: 1, bar: 2 }; let e = {foo: function() {dosomething();}}; let f = { foo: function() { dosomething(); } }; let {} = obj; let { } = obj; let {g} = obj; let { h } = obj; let {i, j} = obj; let { k, l } = obj; let {m, n} = obj; let { o, p } = obj; let {q = function() {dosomething();}} = obj; let { r = function() { dosomething(); } } = obj; ``` ### ObjectExpression and ObjectPattern Examples of **incorrect** code for this rule with the `{ "ObjectExpression": "always", "ObjectPattern": "never" }` options: ``` /\*eslint object-curly-newline: ["error", { "ObjectExpression": "always", "ObjectPattern": "never" }]\*/ /\*eslint-env es6\*/ let a = {}; let b = {foo: 1}; let c = {foo: 1, bar: 2}; let d = {foo: 1, bar: 2}; let e = {foo: function() { dosomething(); }}; let { } = obj; let { f } = obj; let { g, h } = obj; let { i, j } = obj; let { k = function() { dosomething(); } } = obj; ``` Examples of **correct** code for this rule with the `{ "ObjectExpression": "always", "ObjectPattern": "never" }` options: ``` /\*eslint object-curly-newline: ["error", { "ObjectExpression": "always", "ObjectPattern": "never" }]\*/ /\*eslint-env es6\*/ let a = { }; let b = { foo: 1 }; let c = { foo: 1, bar: 2 }; let d = { foo: 1, bar: 2 }; let e = { foo: function() { dosomething(); } }; let {} = obj; let {f} = obj; let {g, h} = obj; let {i, j} = obj; let {k = function() { dosomething(); }} = obj; ``` ### ImportDeclaration and ExportDeclaration Examples of **incorrect** code for this rule with the `{ "ImportDeclaration": "always", "ExportDeclaration": "never" }` options: ``` /\*eslint object-curly-newline: ["error", { "ImportDeclaration": "always", "ExportDeclaration": "never" }]\*/ /\*eslint-env es6\*/ import {foo, bar} from 'foo-bar'; import {foo as f, bar} from 'foo-bar'; import {foo, bar} from 'foo-bar'; export { foo, bar }; export { foo as f, bar } from 'foo-bar'; ``` Examples of **correct** code for this rule with the `{ "ImportDeclaration": "always", "ExportDeclaration": "never" }` options: ``` /\*eslint object-curly-newline: ["error", { "ImportDeclaration": "always", "ExportDeclaration": "never" }]\*/ /\*eslint-env es6\*/ import { foo, bar } from 'foo-bar'; import { foo, bar } from 'foo-bar'; import { foo as f, bar } from 'foo-bar'; export { foo, bar } from 'foo-bar'; export { foo as f, bar } from 'foo-bar'; ``` When Not To Use It ------------------ If you don’t want to enforce consistent line breaks after opening and before closing braces, then it’s safe to disable this rule. Compatibility ------------- * **JSCS**: [requirePaddingNewLinesInObjects](https://jscs-dev.github.io/rule/requirePaddingNewLinesInObjects) * **JSCS**: [disallowPaddingNewLinesInObjects](https://jscs-dev.github.io/rule/disallowPaddingNewLinesInObjects) Related Rules ------------- * <comma-spacing> * <key-spacing> * <object-curly-spacing> * <object-property-newline> Version ------- This rule was introduced in ESLint v2.12.0. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/object-curly-newline.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/object-curly-newline.js) eslint computed-property-spacing computed-property-spacing ========================= Enforce consistent spacing inside computed property brackets 🔧 Fixable Some problems reported by this rule are automatically fixable by the `--fix` [command line](computed-property-spacing../user-guide/command-line-interface#--fix) option While formatting preferences are very personal, a number of style guides require or disallow spaces between computed properties in the following situations: ``` /\*eslint-env es6\*/ var obj = { prop: "value" }; var a = "prop"; var x = obj[a]; // computed property in object member expression var a = "prop"; var obj = { [a]: "value" // computed property key in object literal (ECMAScript 6) }; var obj = { prop: "value" }; var a = "prop"; var { [a]: x } = obj; // computed property key in object destructuring pattern (ECMAScript 6) ``` Rule Details ------------ This rule enforces consistent spacing inside computed property brackets. It either requires or disallows spaces between the brackets and the values inside of them. This rule does not apply to brackets that are separated from the adjacent value by a newline. Options ------- This rule has two options, a string option and an object option. String option: * `"never"` (default) disallows spaces inside computed property brackets * `"always"` requires one or more spaces inside computed property brackets Object option: * `"enforceForClassMembers": true` (default) additionally applies this rule to class members. ### never Examples of **incorrect** code for this rule with the default `"never"` option: ``` /\*eslint computed-property-spacing: ["error", "never"]\*/ /\*eslint-env es6\*/ obj[foo ] obj[ 'foo'] var x = {[ b ]: a} obj[foo[ bar ]] const { [ a ]: someProp } = obj; ({ [ b ]: anotherProp } = anotherObj); ``` Examples of **correct** code for this rule with the default `"never"` option: ``` /\*eslint computed-property-spacing: ["error", "never"]\*/ /\*eslint-env es6\*/ obj[foo] obj['foo'] var x = {[b]: a} obj[foo[bar]] const { [a]: someProp } = obj; ({ [b]: anotherProp } = anotherObj); ``` ### always Examples of **incorrect** code for this rule with the `"always"` option: ``` /\*eslint computed-property-spacing: ["error", "always"]\*/ /\*eslint-env es6\*/ obj[foo] var x = {[b]: a} obj[ foo] obj['foo' ] obj[foo[ bar ]] var x = {[ b]: a} const { [a]: someProp } = obj; ({ [b ]: anotherProp } = anotherObj); ``` Examples of **correct** code for this rule with the `"always"` option: ``` /\*eslint computed-property-spacing: ["error", "always"]\*/ /\*eslint-env es6\*/ obj[ foo ] obj[ 'foo' ] var x = {[ b ]: a} obj[ foo[ bar ] ] const { [ a ]: someProp } = obj; ({ [ b ]: anotherProp } = anotherObj); ``` #### enforceForClassMembers With `enforceForClassMembers` set to `true` (default), the rule also disallows/enforces spaces inside of computed keys of class methods, getters and setters. Examples of **incorrect** code for this rule with `"never"` and `{ "enforceForClassMembers": true }` (default): ``` /\*eslint computed-property-spacing: ["error", "never", { "enforceForClassMembers": true }]\*/ /\*eslint-env es6\*/ class Foo { [a ]() {} get [b ]() {} set [b ](value) {} } const Bar = class { [ a](){} static [ b]() {} static get [ c ]() {} static set [ c ](value) {} } ``` Examples of **correct** code for this rule with `"never"` and `{ "enforceForClassMembers": true }` (default): ``` /\*eslint computed-property-spacing: ["error", "never", { "enforceForClassMembers": true }]\*/ /\*eslint-env es6\*/ class Foo { [a]() {} get [b]() {} set [b](value) {} } const Bar = class { [a](){} static [b]() {} static get [c]() {} static set [c](value) {} } ``` Examples of **correct** code for this rule with `"never"` and `{ "enforceForClassMembers": false }`: ``` /\*eslint computed-property-spacing: ["error", "never", { "enforceForClassMembers": false }]\*/ /\*eslint-env es6\*/ class Foo { [a ]() {} get [b ]() {} set [b ](value) {} } const Bar = class { [ a](){} static [ b]() {} static get [ c ]() {} static set [ c ](value) {} } ``` When Not To Use It ------------------ You can turn this rule off if you are not concerned with the consistency of computed properties. Related Rules ------------- * <array-bracket-spacing> * <comma-spacing> * <space-in-parens> Version ------- This rule was introduced in ESLint v0.23.0. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/computed-property-spacing.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/computed-property-spacing.js)
programming_docs
eslint object-curly-spacing object-curly-spacing ==================== Enforce consistent spacing inside braces 🔧 Fixable Some problems reported by this rule are automatically fixable by the `--fix` [command line](object-curly-spacing../user-guide/command-line-interface#--fix) option While formatting preferences are very personal, a number of style guides require or disallow spaces between curly braces in the following situations: ``` // simple object literals var obj = { foo: "bar" }; // nested object literals var obj = { foo: { zoo: "bar" } }; // destructuring assignment (EcmaScript 6) var { x, y } = y; // import/export declarations (EcmaScript 6) import { foo } from "bar"; export { foo }; ``` Rule Details ------------ This rule enforces consistent spacing inside braces of object literals, destructuring assignments, and import/export specifiers. Options ------- This rule has two options, a string option and an object option. String option: * `"never"` (default) disallows spacing inside of braces * `"always"` requires spacing inside of braces (except `{}`) Object option: * `"arraysInObjects": true` requires spacing inside of braces of objects beginning and/or ending with an array element (applies when the first option is set to `never`) * `"arraysInObjects": false` disallows spacing inside of braces of objects beginning and/or ending with an array element (applies when the first option is set to `always`) * `"objectsInObjects": true` requires spacing inside of braces of objects beginning and/or ending with an object element (applies when the first option is set to `never`) * `"objectsInObjects": false` disallows spacing inside of braces of objects beginning and/or ending with an object element (applies when the first option is set to `always`) ### never Examples of **incorrect** code for this rule with the default `"never"` option: ``` /\*eslint object-curly-spacing: ["error", "never"]\*/ var obj = { 'foo': 'bar' }; var obj = {'foo': 'bar' }; var obj = { baz: {'foo': 'qux'}, bar}; var obj = {baz: { 'foo': 'qux'}, bar}; var {x } = y; import { foo } from 'bar'; ``` Examples of **correct** code for this rule with the default `"never"` option: ``` /\*eslint object-curly-spacing: ["error", "never"]\*/ var obj = {'foo': 'bar'}; var obj = {'foo': {'bar': 'baz'}, 'qux': 'quxx'}; var obj = { 'foo': 'bar' }; var obj = {'foo': 'bar' }; var obj = { 'foo':'bar'}; var obj = {}; var {x} = y; import {foo} from 'bar'; ``` ### always Examples of **incorrect** code for this rule with the `"always"` option: ``` /\*eslint object-curly-spacing: ["error", "always"]\*/ var obj = {'foo': 'bar'}; var obj = {'foo': 'bar' }; var obj = { baz: {'foo': 'qux'}, bar}; var obj = {baz: { 'foo': 'qux' }, bar}; var obj = {'foo': 'bar' }; var obj = { 'foo':'bar'}; var {x} = y; import {foo } from 'bar'; ``` Examples of **correct** code for this rule with the `"always"` option: ``` /\*eslint object-curly-spacing: ["error", "always"]\*/ var obj = {}; var obj = { 'foo': 'bar' }; var obj = { 'foo': { 'bar': 'baz' }, 'qux': 'quxx' }; var obj = { 'foo': 'bar' }; var { x } = y; import { foo } from 'bar'; ``` #### arraysInObjects Examples of additional **correct** code for this rule with the `"never", { "arraysInObjects": true }` options: ``` /\*eslint object-curly-spacing: ["error", "never", { "arraysInObjects": true }]\*/ var obj = {"foo": [ 1, 2 ] }; var obj = {"foo": [ "baz", "bar" ] }; ``` Examples of additional **correct** code for this rule with the `"always", { "arraysInObjects": false }` options: ``` /\*eslint object-curly-spacing: ["error", "always", { "arraysInObjects": false }]\*/ var obj = { "foo": [ 1, 2 ]}; var obj = { "foo": [ "baz", "bar" ]}; ``` #### objectsInObjects Examples of additional **correct** code for this rule with the `"never", { "objectsInObjects": true }` options: ``` /\*eslint object-curly-spacing: ["error", "never", { "objectsInObjects": true }]\*/ var obj = {"foo": {"baz": 1, "bar": 2} }; ``` Examples of additional **correct** code for this rule with the `"always", { "objectsInObjects": false }` options: ``` /\*eslint object-curly-spacing: ["error", "always", { "objectsInObjects": false }]\*/ var obj = { "foo": { "baz": 1, "bar": 2 }}; ``` When Not To Use It ------------------ You can turn this rule off if you are not concerned with the consistency of spacing between curly braces. Related Rules ------------- * <array-bracket-spacing> * <comma-spacing> * <computed-property-spacing> * <space-in-parens> Version ------- This rule was introduced in ESLint v0.22.0. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/object-curly-spacing.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/object-curly-spacing.js) eslint generator-star-spacing generator-star-spacing ====================== Enforce consistent spacing around `*` operators in generator functions 🔧 Fixable Some problems reported by this rule are automatically fixable by the `--fix` [command line](generator-star-spacing../user-guide/command-line-interface#--fix) option Generators are a new type of function in ECMAScript 6 that can return multiple values over time. These special functions are indicated by placing an `*` after the `function` keyword. Here is an example of a generator function: ``` /\*eslint-env es6\*/ function\* generator() { yield "44"; yield "55"; } ``` This is also valid: ``` /\*eslint-env es6\*/ function \*generator() { yield "44"; yield "55"; } ``` This is valid as well: ``` /\*eslint-env es6\*/ function \* generator() { yield "44"; yield "55"; } ``` To keep a sense of consistency when using generators this rule enforces a single position for the `*`. Rule Details ------------ This rule aims to enforce spacing around the `*` of generator functions. Options ------- The rule takes one option, an object, which has two keys `before` and `after` having boolean values `true` or `false`. * `before` enforces spacing between the `*` and the `function` keyword. If it is `true`, a space is required, otherwise spaces are disallowed. In object literal shorthand methods, spacing before the `*` is not checked, as they lack a `function` keyword. * `after` enforces spacing between the `*` and the function name (or the opening parenthesis for anonymous generator functions). If it is `true`, a space is required, otherwise spaces are disallowed. The default is `{"before": true, "after": false}`. An example configuration: ``` "generator-star-spacing": ["error", {"before": true, "after": false}] ``` And the option has shorthand as a string keyword: * `{"before": true, "after": false}` → `"before"` * `{"before": false, "after": true}` → `"after"` * `{"before": true, "after": true}` → `"both"` * `{"before": false, "after": false}` → `"neither"` An example of shorthand configuration: ``` "generator-star-spacing": ["error", "after"] ``` Additionally, this rule allows further configurability via overrides per function type. * `named` provides overrides for named functions * `anonymous` provides overrides for anonymous functions * `method` provides overrides for class methods or property function shorthand An example of a configuration with overrides: ``` "generator-star-spacing": ["error", { "before": false, "after": true, "anonymous": "neither", "method": {"before": true, "after": true} }] ``` In the example configuration above, the top level “before” and “after” options define the default behavior of the rule, while the “anonymous” and “method” options override the default behavior. Overrides can be either an object with “before” and “after”, or a shorthand string as above. Examples -------- ### before Examples of **correct** code for this rule with the `"before"` option: ``` /\*eslint generator-star-spacing: ["error", {"before": true, "after": false}]\*/ /\*eslint-env es6\*/ function \*generator() {} var anonymous = function \*() {}; var shorthand = { \*generator() {} }; ``` ### after Examples of **correct** code for this rule with the `"after"` option: ``` /\*eslint generator-star-spacing: ["error", {"before": false, "after": true}]\*/ /\*eslint-env es6\*/ function\* generator() {} var anonymous = function\* () {}; var shorthand = { \* generator() {} }; ``` ### both Examples of **correct** code for this rule with the `"both"` option: ``` /\*eslint generator-star-spacing: ["error", {"before": true, "after": true}]\*/ /\*eslint-env es6\*/ function \* generator() {} var anonymous = function \* () {}; var shorthand = { \* generator() {} }; ``` ### neither Examples of **correct** code for this rule with the `"neither"` option: ``` /\*eslint generator-star-spacing: ["error", {"before": false, "after": false}]\*/ /\*eslint-env es6\*/ function\*generator() {} var anonymous = function\*() {}; var shorthand = { \*generator() {} }; ``` Examples of **incorrect** code for this rule with overrides present: ``` /\*eslint generator-star-spacing: ["error", { "before": false, "after": true, "anonymous": "neither", "method": {"before": true, "after": true} }]\*/ /\*eslint-env es6\*/ function \* generator() {} var anonymous = function\* () {}; var shorthand = { \*generator() {} }; class Class { static\* method() {} } ``` Examples of **correct** code for this rule with overrides present: ``` /\*eslint generator-star-spacing: ["error", { "before": false, "after": true, "anonymous": "neither", "method": {"before": true, "after": true} }]\*/ /\*eslint-env es6\*/ function\* generator() {} var anonymous = function\*() {}; var shorthand = { \* generator() {} }; class Class { static \* method() {} } ``` When Not To Use It ------------------ If your project will not be using generators or you are not concerned with spacing consistency, you do not need this rule. Version ------- This rule was introduced in ESLint v0.17.0. Further Reading --------------- [Read Understanding ECMAScript 6 | Leanpub](https://leanpub.com/understandinges6/read/#leanpub-auto-generators) Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/generator-star-spacing.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/generator-star-spacing.js) eslint no-loss-of-precision no-loss-of-precision ==================== Disallow literal numbers that lose precision ✅ Recommended The `"extends": "eslint:recommended"` property in a [configuration file](no-loss-of-precision../user-guide/configuring/configuration-files#extending-configuration-files) enables this rule This rule would disallow the use of number literals that lose precision at runtime when converted to a JS `Number` due to 64-bit floating-point rounding. Rule Details ------------ In JS, `Number`s are stored as double-precision floating-point numbers according to the [IEEE 754 standard](https://en.wikipedia.org/wiki/IEEE_754). Because of this, numbers can only retain accuracy up to a certain amount of digits. If the programmer enters additional digits, those digits will be lost in the conversion to the `Number` type and will result in unexpected behavior. Examples of **incorrect** code for this rule: ``` /\*eslint no-loss-of-precision: "error"\*/ const x = 9007199254740993 const x = 5123000000000000000000000000001 const x = 1230000000000000000000000.0 const x = .1230000000000000000000000 const x = 0X20000000000001 const x = 0X2\_000000000\_0001; ``` Examples of **correct** code for this rule: ``` /\*eslint no-loss-of-precision: "error"\*/ const x = 12345 const x = 123.456 const x = 123e34 const x = 12300000000000000000000000 const x = 0x1FFFFFFFFFFFFF const x = 9007199254740991 const x = 9007\_1992547409\_91 ``` Version ------- This rule was introduced in ESLint v7.1.0. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/no-loss-of-precision.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/no-loss-of-precision.js) eslint no-continue no-continue =========== Disallow `continue` statements The `continue` statement terminates execution of the statements in the current iteration of the current or labeled loop, and continues execution of the loop with the next iteration. When used incorrectly it makes code less testable, less readable and less maintainable. Structured control flow statements such as `if` should be used instead. ``` var sum = 0, i; for(i = 0; i < 10; i++) { if(i >= 5) { continue; } a += i; } ``` Rule Details ------------ This rule disallows `continue` statements. Examples of **incorrect** code for this rule: ``` /\*eslint no-continue: "error"\*/ var sum = 0, i; for(i = 0; i < 10; i++) { if(i >= 5) { continue; } a += i; } ``` ``` /\*eslint no-continue: "error"\*/ var sum = 0, i; labeledLoop: for(i = 0; i < 10; i++) { if(i >= 5) { continue labeledLoop; } a += i; } ``` Examples of **correct** code for this rule: ``` /\*eslint no-continue: "error"\*/ var sum = 0, i; for(i = 0; i < 10; i++) { if(i < 5) { a += i; } } ``` Compatibility ------------- * **JSLint**: `continue` Version ------- This rule was introduced in ESLint v0.19.0. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/no-continue.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/no-continue.js) eslint no-unused-private-class-members no-unused-private-class-members =============================== Disallow unused private class members Private class members that are declared and not used anywhere in the code are most likely an error due to incomplete refactoring. Such class members take up space in the code and can lead to confusion by readers. Rule Details ------------ This rule reports unused private class members. * A private field or method is considered to be unused if its value is never read. * A private accessor is considered to be unused if it is never accessed (read or write). Examples of **incorrect** code for this rule: ``` /\*eslint no-unused-private-class-members: "error"\*/ class Foo { #unusedMember = 5; } class Foo { #usedOnlyInWrite = 5; method() { this.#usedOnlyInWrite = 42; } } class Foo { #usedOnlyToUpdateItself = 5; method() { this.#usedOnlyToUpdateItself++; } } class Foo { #unusedMethod() {} } class Foo { get #unusedAccessor() {} set #unusedAccessor(value) {} } ``` Examples of **correct** code for this rule: ``` /\*eslint no-unused-private-class-members: "error"\*/ class Foo { #usedMember = 42; method() { return this.#usedMember; } } class Foo { #usedMethod() { return 42; } anotherMethod() { return this.#usedMethod(); } } class Foo { get #usedAccessor() {} set #usedAccessor(value) {} method() { this.#usedAccessor = 42; } } ``` When Not To Use It ------------------ If you don’t want to be notified about unused private class members, you can safely turn this rule off. Version ------- This rule was introduced in ESLint v8.1.0. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/no-unused-private-class-members.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/no-unused-private-class-members.js) eslint Rules Rules ===== Rules in ESLint are grouped by type to help you understand their purpose. Each rule has emojis denoting: ✅ Recommended The `"extends": "eslint:recommended"` property in a [configuration file](../user-guide/configuring/configuration-files#extending-configuration-files) enables this rule 🔧 Fixable Some problems reported by this rule are automatically fixable by the `--fix` [command line](../user-guide/command-line-interface#--fix) option 💡 hasSuggestions Some problems reported by this rule are manually fixable by editor [suggestions](../developer-guide/working-with-rules#providing-suggestions) Possible Problems ------------------ These rules relate to possible logic errors in code: <array-callback-return> Enforce `return` statements in callbacks of array methods Categories: ✅ Extends 🔧 Fix 💡 Suggestions <constructor-super> Require `super()` calls in constructors Categories: ✅ Extends 🔧 Fix 💡 Suggestions <for-direction> Enforce "for" loop update clause moving the counter in the right direction Categories: ✅ Extends 🔧 Fix 💡 Suggestions <getter-return> Enforce `return` statements in getters Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-async-promise-executor> Disallow using an async function as a Promise executor Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-await-in-loop> Disallow `await` inside of loops Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-class-assign> Disallow reassigning class members Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-compare-neg-zero> Disallow comparing against -0 Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-cond-assign> Disallow assignment operators in conditional expressions Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-const-assign> Disallow reassigning `const` variables Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-constant-binary-expression> Disallow expressions where the operation doesn't affect the value Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-constant-condition> Disallow constant expressions in conditions Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-constructor-return> Disallow returning value from constructor Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-control-regex> Disallow control characters in regular expressions Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-debugger> Disallow the use of `debugger` Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-dupe-args> Disallow duplicate arguments in `function` definitions Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-dupe-class-members> Disallow duplicate class members Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-dupe-else-if> Disallow duplicate conditions in if-else-if chains Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-dupe-keys> Disallow duplicate keys in object literals Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-duplicate-case> Disallow duplicate case labels Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-duplicate-imports> Disallow duplicate module imports Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-empty-character-class> Disallow empty character classes in regular expressions Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-empty-pattern> Disallow empty destructuring patterns Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-ex-assign> Disallow reassigning exceptions in `catch` clauses Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-fallthrough> Disallow fallthrough of `case` statements Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-func-assign> Disallow reassigning `function` declarations Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-import-assign> Disallow assigning to imported bindings Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-inner-declarations> Disallow variable or `function` declarations in nested blocks Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-invalid-regexp> Disallow invalid regular expression strings in `RegExp` constructors Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-irregular-whitespace> Disallow irregular whitespace Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-loss-of-precision> Disallow literal numbers that lose precision Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-misleading-character-class> Disallow characters which are made with multiple code points in character class syntax Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-new-native-nonconstructor> Disallow `new` operators with global non-constructor functions Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-new-symbol> Disallow `new` operators with the `Symbol` object Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-obj-calls> Disallow calling global object properties as functions Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-promise-executor-return> Disallow returning values from Promise executor functions Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-prototype-builtins> Disallow calling some `Object.prototype` methods directly on objects Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-self-assign> Disallow assignments where both sides are exactly the same Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-self-compare> Disallow comparisons where both sides are exactly the same Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-setter-return> Disallow returning values from setters Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-sparse-arrays> Disallow sparse arrays Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-template-curly-in-string> Disallow template literal placeholder syntax in regular strings Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-this-before-super> Disallow `this`/`super` before calling `super()` in constructors Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-undef> Disallow the use of undeclared variables unless mentioned in `/\*global \*/` comments Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-unexpected-multiline> Disallow confusing multiline expressions Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-unmodified-loop-condition> Disallow unmodified loop conditions Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-unreachable> Disallow unreachable code after `return`, `throw`, `continue`, and `break` statements Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-unreachable-loop> Disallow loops with a body that allows only one iteration Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-unsafe-finally> Disallow control flow statements in `finally` blocks Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-unsafe-negation> Disallow negating the left operand of relational operators Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-unsafe-optional-chaining> Disallow use of optional chaining in contexts where the `undefined` value is not allowed Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-unused-private-class-members> Disallow unused private class members Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-unused-vars> Disallow unused variables Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-use-before-define> Disallow the use of variables before they are defined Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-useless-backreference> Disallow useless backreferences in regular expressions Categories: ✅ Extends 🔧 Fix 💡 Suggestions <require-atomic-updates> Disallow assignments that can lead to race conditions due to usage of `await` or `yield` Categories: ✅ Extends 🔧 Fix 💡 Suggestions <use-isnan> Require calls to `isNaN()` when checking for `NaN` Categories: ✅ Extends 🔧 Fix 💡 Suggestions <valid-typeof> Enforce comparing `typeof` expressions against valid strings Categories: ✅ Extends 🔧 Fix 💡 Suggestions Suggestions ------------ These rules suggest alternate ways of doing things: <accessor-pairs> Enforce getter and setter pairs in objects and classes Categories: ✅ Extends 🔧 Fix 💡 Suggestions <arrow-body-style> Require braces around arrow function bodies Categories: ✅ Extends 🔧 Fix 💡 Suggestions <block-scoped-var> Enforce the use of variables within the scope they are defined Categories: ✅ Extends 🔧 Fix 💡 Suggestions <camelcase> Enforce camelcase naming convention Categories: ✅ Extends 🔧 Fix 💡 Suggestions <capitalized-comments> Enforce or disallow capitalization of the first letter of a comment Categories: ✅ Extends 🔧 Fix 💡 Suggestions <class-methods-use-this> Enforce that class methods utilize `this` Categories: ✅ Extends 🔧 Fix 💡 Suggestions <complexity> Enforce a maximum cyclomatic complexity allowed in a program Categories: ✅ Extends 🔧 Fix 💡 Suggestions <consistent-return> Require `return` statements to either always or never specify values Categories: ✅ Extends 🔧 Fix 💡 Suggestions <consistent-this> Enforce consistent naming when capturing the current execution context Categories: ✅ Extends 🔧 Fix 💡 Suggestions <curly> Enforce consistent brace style for all control statements Categories: ✅ Extends 🔧 Fix 💡 Suggestions <default-case> Require `default` cases in `switch` statements Categories: ✅ Extends 🔧 Fix 💡 Suggestions <default-case-last> Enforce default clauses in switch statements to be last Categories: ✅ Extends 🔧 Fix 💡 Suggestions <default-param-last> Enforce default parameters to be last Categories: ✅ Extends 🔧 Fix 💡 Suggestions <dot-notation> Enforce dot notation whenever possible Categories: ✅ Extends 🔧 Fix 💡 Suggestions <eqeqeq> Require the use of `===` and `!==` Categories: ✅ Extends 🔧 Fix 💡 Suggestions <func-name-matching> Require function names to match the name of the variable or property to which they are assigned Categories: ✅ Extends 🔧 Fix 💡 Suggestions <func-names> Require or disallow named `function` expressions Categories: ✅ Extends 🔧 Fix 💡 Suggestions <func-style> Enforce the consistent use of either `function` declarations or expressions Categories: ✅ Extends 🔧 Fix 💡 Suggestions <grouped-accessor-pairs> Require grouped accessor pairs in object literals and classes Categories: ✅ Extends 🔧 Fix 💡 Suggestions <guard-for-in> Require `for-in` loops to include an `if` statement Categories: ✅ Extends 🔧 Fix 💡 Suggestions <id-denylist> Disallow specified identifiers Categories: ✅ Extends 🔧 Fix 💡 Suggestions <id-length> Enforce minimum and maximum identifier lengths Categories: ✅ Extends 🔧 Fix 💡 Suggestions <id-match> Require identifiers to match a specified regular expression Categories: ✅ Extends 🔧 Fix 💡 Suggestions <init-declarations> Require or disallow initialization in variable declarations Categories: ✅ Extends 🔧 Fix 💡 Suggestions <logical-assignment-operators> Require or disallow logical assignment logical operator shorthand Categories: ✅ Extends 🔧 Fix 💡 Suggestions <max-classes-per-file> Enforce a maximum number of classes per file Categories: ✅ Extends 🔧 Fix 💡 Suggestions <max-depth> Enforce a maximum depth that blocks can be nested Categories: ✅ Extends 🔧 Fix 💡 Suggestions <max-lines> Enforce a maximum number of lines per file Categories: ✅ Extends 🔧 Fix 💡 Suggestions <max-lines-per-function> Enforce a maximum number of lines of code in a function Categories: ✅ Extends 🔧 Fix 💡 Suggestions <max-nested-callbacks> Enforce a maximum depth that callbacks can be nested Categories: ✅ Extends 🔧 Fix 💡 Suggestions <max-params> Enforce a maximum number of parameters in function definitions Categories: ✅ Extends 🔧 Fix 💡 Suggestions <max-statements> Enforce a maximum number of statements allowed in function blocks Categories: ✅ Extends 🔧 Fix 💡 Suggestions <multiline-comment-style> Enforce a particular style for multiline comments Categories: ✅ Extends 🔧 Fix 💡 Suggestions <new-cap> Require constructor names to begin with a capital letter Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-alert> Disallow the use of `alert`, `confirm`, and `prompt` Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-array-constructor> Disallow `Array` constructors Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-bitwise> Disallow bitwise operators Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-caller> Disallow the use of `arguments.caller` or `arguments.callee` Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-case-declarations> Disallow lexical declarations in case clauses Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-confusing-arrow> Disallow arrow functions where they could be confused with comparisons Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-console> Disallow the use of `console` Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-continue> Disallow `continue` statements Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-delete-var> Disallow deleting variables Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-div-regex> Disallow division operators explicitly at the beginning of regular expressions Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-else-return> Disallow `else` blocks after `return` statements in `if` statements Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-empty> Disallow empty block statements Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-empty-function> Disallow empty functions Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-empty-static-block> Disallow empty static blocks Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-eq-null> Disallow `null` comparisons without type-checking operators Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-eval> Disallow the use of `eval()` Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-extend-native> Disallow extending native types Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-extra-bind> Disallow unnecessary calls to `.bind()` Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-extra-boolean-cast> Disallow unnecessary boolean casts Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-extra-label> Disallow unnecessary labels Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-extra-semi> Disallow unnecessary semicolons Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-floating-decimal> Disallow leading or trailing decimal points in numeric literals Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-global-assign> Disallow assignments to native objects or read-only global variables Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-implicit-coercion> Disallow shorthand type conversions Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-implicit-globals> Disallow declarations in the global scope Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-implied-eval> Disallow the use of `eval()`-like methods Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-inline-comments> Disallow inline comments after code Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-invalid-this> Disallow use of `this` in contexts where the value of `this` is `undefined` Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-iterator> Disallow the use of the `\_\_iterator\_\_` property Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-label-var> Disallow labels that share a name with a variable Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-labels> Disallow labeled statements Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-lone-blocks> Disallow unnecessary nested blocks Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-lonely-if> Disallow `if` statements as the only statement in `else` blocks Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-loop-func> Disallow function declarations that contain unsafe references inside loop statements Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-magic-numbers> Disallow magic numbers Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-mixed-operators> Disallow mixed binary operators Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-multi-assign> Disallow use of chained assignment expressions Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-multi-str> Disallow multiline strings Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-negated-condition> Disallow negated conditions Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-nested-ternary> Disallow nested ternary expressions Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-new> Disallow `new` operators outside of assignments or comparisons Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-new-func> Disallow `new` operators with the `Function` object Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-new-object> Disallow `Object` constructors Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-new-wrappers> Disallow `new` operators with the `String`, `Number`, and `Boolean` objects Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-nonoctal-decimal-escape> Disallow `\8` and `\9` escape sequences in string literals Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-octal> Disallow octal literals Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-octal-escape> Disallow octal escape sequences in string literals Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-param-reassign> Disallow reassigning `function` parameters Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-plusplus> Disallow the unary operators `++` and `--` Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-proto> Disallow the use of the `\_\_proto\_\_` property Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-redeclare> Disallow variable redeclaration Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-regex-spaces> Disallow multiple spaces in regular expressions Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-restricted-exports> Disallow specified names in exports Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-restricted-globals> Disallow specified global variables Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-restricted-imports> Disallow specified modules when loaded by `import` Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-restricted-properties> Disallow certain properties on certain objects Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-restricted-syntax> Disallow specified syntax Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-return-assign> Disallow assignment operators in `return` statements Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-return-await> Disallow unnecessary `return await` Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-script-url> Disallow `javascript:` urls Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-sequences> Disallow comma operators Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-shadow> Disallow variable declarations from shadowing variables declared in the outer scope Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-shadow-restricted-names> Disallow identifiers from shadowing restricted names Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-ternary> Disallow ternary operators Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-throw-literal> Disallow throwing literals as exceptions Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-undef-init> Disallow initializing variables to `undefined` Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-undefined> Disallow the use of `undefined` as an identifier Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-underscore-dangle> Disallow dangling underscores in identifiers Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-unneeded-ternary> Disallow ternary operators when simpler alternatives exist Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-unused-expressions> Disallow unused expressions Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-unused-labels> Disallow unused labels Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-useless-call> Disallow unnecessary calls to `.call()` and `.apply()` Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-useless-catch> Disallow unnecessary `catch` clauses Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-useless-computed-key> Disallow unnecessary computed property keys in objects and classes Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-useless-concat> Disallow unnecessary concatenation of literals or template literals Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-useless-constructor> Disallow unnecessary constructors Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-useless-escape> Disallow unnecessary escape characters Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-useless-rename> Disallow renaming import, export, and destructured assignments to the same name Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-useless-return> Disallow redundant return statements Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-var> Require `let` or `const` instead of `var` Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-void> Disallow `void` operators Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-warning-comments> Disallow specified warning terms in comments Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-with> Disallow `with` statements Categories: ✅ Extends 🔧 Fix 💡 Suggestions <object-shorthand> Require or disallow method and property shorthand syntax for object literals Categories: ✅ Extends 🔧 Fix 💡 Suggestions <one-var> Enforce variables to be declared either together or separately in functions Categories: ✅ Extends 🔧 Fix 💡 Suggestions <one-var-declaration-per-line> Require or disallow newlines around variable declarations Categories: ✅ Extends 🔧 Fix 💡 Suggestions <operator-assignment> Require or disallow assignment operator shorthand where possible Categories: ✅ Extends 🔧 Fix 💡 Suggestions <prefer-arrow-callback> Require using arrow functions for callbacks Categories: ✅ Extends 🔧 Fix 💡 Suggestions <prefer-const> Require `const` declarations for variables that are never reassigned after declared Categories: ✅ Extends 🔧 Fix 💡 Suggestions <prefer-destructuring> Require destructuring from arrays and/or objects Categories: ✅ Extends 🔧 Fix 💡 Suggestions <prefer-exponentiation-operator> Disallow the use of `Math.pow` in favor of the `\*\*` operator Categories: ✅ Extends 🔧 Fix 💡 Suggestions <prefer-named-capture-group> Enforce using named capture group in regular expression Categories: ✅ Extends 🔧 Fix 💡 Suggestions <prefer-numeric-literals> Disallow `parseInt()` and `Number.parseInt()` in favor of binary, octal, and hexadecimal literals Categories: ✅ Extends 🔧 Fix 💡 Suggestions <prefer-object-has-own> Disallow use of `Object.prototype.hasOwnProperty.call()` and prefer use of `Object.hasOwn()` Categories: ✅ Extends 🔧 Fix 💡 Suggestions <prefer-object-spread> Disallow using Object.assign with an object literal as the first argument and prefer the use of object spread instead Categories: ✅ Extends 🔧 Fix 💡 Suggestions <prefer-promise-reject-errors> Require using Error objects as Promise rejection reasons Categories: ✅ Extends 🔧 Fix 💡 Suggestions <prefer-regex-literals> Disallow use of the `RegExp` constructor in favor of regular expression literals Categories: ✅ Extends 🔧 Fix 💡 Suggestions <prefer-rest-params> Require rest parameters instead of `arguments` Categories: ✅ Extends 🔧 Fix 💡 Suggestions <prefer-spread> Require spread operators instead of `.apply()` Categories: ✅ Extends 🔧 Fix 💡 Suggestions <prefer-template> Require template literals instead of string concatenation Categories: ✅ Extends 🔧 Fix 💡 Suggestions <quote-props> Require quotes around object literal property names Categories: ✅ Extends 🔧 Fix 💡 Suggestions <radix> Enforce the consistent use of the radix argument when using `parseInt()` Categories: ✅ Extends 🔧 Fix 💡 Suggestions <require-await> Disallow async functions which have no `await` expression Categories: ✅ Extends 🔧 Fix 💡 Suggestions <require-unicode-regexp> Enforce the use of `u` flag on RegExp Categories: ✅ Extends 🔧 Fix 💡 Suggestions <require-yield> Require generator functions to contain `yield` Categories: ✅ Extends 🔧 Fix 💡 Suggestions <sort-imports> Enforce sorted import declarations within modules Categories: ✅ Extends 🔧 Fix 💡 Suggestions <sort-keys> Require object keys to be sorted Categories: ✅ Extends 🔧 Fix 💡 Suggestions <sort-vars> Require variables within the same declaration block to be sorted Categories: ✅ Extends 🔧 Fix 💡 Suggestions <spaced-comment> Enforce consistent spacing after the `//` or `/\*` in a comment Categories: ✅ Extends 🔧 Fix 💡 Suggestions <strict> Require or disallow strict mode directives Categories: ✅ Extends 🔧 Fix 💡 Suggestions <symbol-description> Require symbol descriptions Categories: ✅ Extends 🔧 Fix 💡 Suggestions <vars-on-top> Require `var` declarations be placed at the top of their containing scope Categories: ✅ Extends 🔧 Fix 💡 Suggestions <yoda> Require or disallow "Yoda" conditions Categories: ✅ Extends 🔧 Fix 💡 Suggestions Layout & Formatting -------------------- These rules care about how the code looks rather than how it executes: <array-bracket-newline> Enforce linebreaks after opening and before closing array brackets Categories: ✅ Extends 🔧 Fix 💡 Suggestions <array-bracket-spacing> Enforce consistent spacing inside array brackets Categories: ✅ Extends 🔧 Fix 💡 Suggestions <array-element-newline> Enforce line breaks after each array element Categories: ✅ Extends 🔧 Fix 💡 Suggestions <arrow-parens> Require parentheses around arrow function arguments Categories: ✅ Extends 🔧 Fix 💡 Suggestions <arrow-spacing> Enforce consistent spacing before and after the arrow in arrow functions Categories: ✅ Extends 🔧 Fix 💡 Suggestions <block-spacing> Disallow or enforce spaces inside of blocks after opening block and before closing block Categories: ✅ Extends 🔧 Fix 💡 Suggestions <brace-style> Enforce consistent brace style for blocks Categories: ✅ Extends 🔧 Fix 💡 Suggestions <comma-dangle> Require or disallow trailing commas Categories: ✅ Extends 🔧 Fix 💡 Suggestions <comma-spacing> Enforce consistent spacing before and after commas Categories: ✅ Extends 🔧 Fix 💡 Suggestions <comma-style> Enforce consistent comma style Categories: ✅ Extends 🔧 Fix 💡 Suggestions <computed-property-spacing> Enforce consistent spacing inside computed property brackets Categories: ✅ Extends 🔧 Fix 💡 Suggestions <dot-location> Enforce consistent newlines before and after dots Categories: ✅ Extends 🔧 Fix 💡 Suggestions <eol-last> Require or disallow newline at the end of files Categories: ✅ Extends 🔧 Fix 💡 Suggestions <func-call-spacing> Require or disallow spacing between function identifiers and their invocations Categories: ✅ Extends 🔧 Fix 💡 Suggestions <function-call-argument-newline> Enforce line breaks between arguments of a function call Categories: ✅ Extends 🔧 Fix 💡 Suggestions <function-paren-newline> Enforce consistent line breaks inside function parentheses Categories: ✅ Extends 🔧 Fix 💡 Suggestions <generator-star-spacing> Enforce consistent spacing around `\*` operators in generator functions Categories: ✅ Extends 🔧 Fix 💡 Suggestions <implicit-arrow-linebreak> Enforce the location of arrow function bodies Categories: ✅ Extends 🔧 Fix 💡 Suggestions <indent> Enforce consistent indentation Categories: ✅ Extends 🔧 Fix 💡 Suggestions <jsx-quotes> Enforce the consistent use of either double or single quotes in JSX attributes Categories: ✅ Extends 🔧 Fix 💡 Suggestions <key-spacing> Enforce consistent spacing between keys and values in object literal properties Categories: ✅ Extends 🔧 Fix 💡 Suggestions <keyword-spacing> Enforce consistent spacing before and after keywords Categories: ✅ Extends 🔧 Fix 💡 Suggestions <line-comment-position> Enforce position of line comments Categories: ✅ Extends 🔧 Fix 💡 Suggestions <linebreak-style> Enforce consistent linebreak style Categories: ✅ Extends 🔧 Fix 💡 Suggestions <lines-around-comment> Require empty lines around comments Categories: ✅ Extends 🔧 Fix 💡 Suggestions <lines-between-class-members> Require or disallow an empty line between class members Categories: ✅ Extends 🔧 Fix 💡 Suggestions <max-len> Enforce a maximum line length Categories: ✅ Extends 🔧 Fix 💡 Suggestions <max-statements-per-line> Enforce a maximum number of statements allowed per line Categories: ✅ Extends 🔧 Fix 💡 Suggestions <multiline-ternary> Enforce newlines between operands of ternary expressions Categories: ✅ Extends 🔧 Fix 💡 Suggestions <new-parens> Enforce or disallow parentheses when invoking a constructor with no arguments Categories: ✅ Extends 🔧 Fix 💡 Suggestions <newline-per-chained-call> Require a newline after each call in a method chain Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-extra-parens> Disallow unnecessary parentheses Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-mixed-spaces-and-tabs> Disallow mixed spaces and tabs for indentation Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-multi-spaces> Disallow multiple spaces Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-multiple-empty-lines> Disallow multiple empty lines Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-tabs> Disallow all tabs Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-trailing-spaces> Disallow trailing whitespace at the end of lines Categories: ✅ Extends 🔧 Fix 💡 Suggestions <no-whitespace-before-property> Disallow whitespace before properties Categories: ✅ Extends 🔧 Fix 💡 Suggestions <nonblock-statement-body-position> Enforce the location of single-line statements Categories: ✅ Extends 🔧 Fix 💡 Suggestions <object-curly-newline> Enforce consistent line breaks after opening and before closing braces Categories: ✅ Extends 🔧 Fix 💡 Suggestions <object-curly-spacing> Enforce consistent spacing inside braces Categories: ✅ Extends 🔧 Fix 💡 Suggestions <object-property-newline> Enforce placing object properties on separate lines Categories: ✅ Extends 🔧 Fix 💡 Suggestions <operator-linebreak> Enforce consistent linebreak style for operators Categories: ✅ Extends 🔧 Fix 💡 Suggestions <padded-blocks> Require or disallow padding within blocks Categories: ✅ Extends 🔧 Fix 💡 Suggestions <padding-line-between-statements> Require or disallow padding lines between statements Categories: ✅ Extends 🔧 Fix 💡 Suggestions <quotes> Enforce the consistent use of either backticks, double, or single quotes Categories: ✅ Extends 🔧 Fix 💡 Suggestions <rest-spread-spacing> Enforce spacing between rest and spread operators and their expressions Categories: ✅ Extends 🔧 Fix 💡 Suggestions <semi> Require or disallow semicolons instead of ASI Categories: ✅ Extends 🔧 Fix 💡 Suggestions <semi-spacing> Enforce consistent spacing before and after semicolons Categories: ✅ Extends 🔧 Fix 💡 Suggestions <semi-style> Enforce location of semicolons Categories: ✅ Extends 🔧 Fix 💡 Suggestions <space-before-blocks> Enforce consistent spacing before blocks Categories: ✅ Extends 🔧 Fix 💡 Suggestions <space-before-function-paren> Enforce consistent spacing before `function` definition opening parenthesis Categories: ✅ Extends 🔧 Fix 💡 Suggestions <space-in-parens> Enforce consistent spacing inside parentheses Categories: ✅ Extends 🔧 Fix 💡 Suggestions <space-infix-ops> Require spacing around infix operators Categories: ✅ Extends 🔧 Fix 💡 Suggestions <space-unary-ops> Enforce consistent spacing before or after unary operators Categories: ✅ Extends 🔧 Fix 💡 Suggestions <switch-colon-spacing> Enforce spacing around colons of switch statements Categories: ✅ Extends 🔧 Fix 💡 Suggestions <template-curly-spacing> Require or disallow spacing around embedded expressions of template strings Categories: ✅ Extends 🔧 Fix 💡 Suggestions <template-tag-spacing> Require or disallow spacing between template tags and their literals Categories: ✅ Extends 🔧 Fix 💡 Suggestions <unicode-bom> Require or disallow Unicode byte order mark (BOM) Categories: ✅ Extends 🔧 Fix 💡 Suggestions <wrap-iife> Require parentheses around immediate `function` invocations Categories: ✅ Extends 🔧 Fix 💡 Suggestions <wrap-regex> Require parenthesis around regex literals Categories: ✅ Extends 🔧 Fix 💡 Suggestions <yield-star-spacing> Require or disallow spacing around the `\*` in `yield\*` expressions Categories: ✅ Extends 🔧 Fix 💡 Suggestions Deprecated ---------- These rules have been deprecated in accordance with the [deprecation policy](https://eslint.org/docs/user-guide/rule-deprecation), and replaced by newer rules: callback-return deprecated Categories:❌ 🔧 Fix 💡 Suggestions global-require deprecated Categories:❌ 🔧 Fix 💡 Suggestions handle-callback-err deprecated Categories:❌ 🔧 Fix 💡 Suggestions id-blacklist deprecated Replaced by [`id-denylist`](id-denylist) Categories:❌ 🔧 Fix 💡 Suggestions indent-legacy deprecated Replaced by [`indent`](indent) Categories:❌ 🔧 Fix 💡 Suggestions lines-around-directive deprecated Replaced by [`padding-line-between-statements`](padding-line-between-statements) Categories:❌ 🔧 Fix 💡 Suggestions newline-after-var deprecated Replaced by [`padding-line-between-statements`](padding-line-between-statements) Categories:❌ 🔧 Fix 💡 Suggestions newline-before-return deprecated Replaced by [`padding-line-between-statements`](padding-line-between-statements) Categories:❌ 🔧 Fix 💡 Suggestions no-buffer-constructor deprecated Categories:❌ 🔧 Fix 💡 Suggestions no-catch-shadow deprecated Replaced by [`no-shadow`](no-shadow) Categories:❌ 🔧 Fix 💡 Suggestions no-mixed-requires deprecated Categories:❌ 🔧 Fix 💡 Suggestions no-native-reassign deprecated Replaced by [`no-global-assign`](no-global-assign) Categories:❌ 🔧 Fix 💡 Suggestions no-negated-in-lhs deprecated Replaced by [`no-unsafe-negation`](no-unsafe-negation) Categories:❌ 🔧 Fix 💡 Suggestions no-new-require deprecated Categories:❌ 🔧 Fix 💡 Suggestions no-path-concat deprecated Categories:❌ 🔧 Fix 💡 Suggestions no-process-env deprecated Categories:❌ 🔧 Fix 💡 Suggestions no-process-exit deprecated Categories:❌ 🔧 Fix 💡 Suggestions no-restricted-modules deprecated Categories:❌ 🔧 Fix 💡 Suggestions no-spaced-func deprecated Replaced by [`func-call-spacing`](func-call-spacing) Categories:❌ 🔧 Fix 💡 Suggestions no-sync deprecated Categories:❌ 🔧 Fix 💡 Suggestions prefer-reflect deprecated Categories:❌ 🔧 Fix 💡 Suggestions require-jsdoc deprecated Categories:❌ 🔧 Fix 💡 Suggestions valid-jsdoc deprecated Categories:❌ 🔧 Fix 💡 Suggestions Removed ------- These rules from older versions of ESLint (before the [deprecation policy](https://eslint.org/docs/user-guide/rule-deprecation) existed) have been replaced by newer rules: generator-star removed Replaced by [`generator-star-spacing`](generator-star-spacing) Categories:❌ 🔧 Fix 💡 Suggestions global-strict removed Replaced by [`strict`](strict) Categories:❌ 🔧 Fix 💡 Suggestions no-arrow-condition removed Replaced by [`no-confusing-arrow`](no-confusing-arrow)[`no-constant-condition`](no-constant-condition) Categories:❌ 🔧 Fix 💡 Suggestions no-comma-dangle removed Replaced by [`comma-dangle`](comma-dangle) Categories:❌ 🔧 Fix 💡 Suggestions no-empty-class removed Replaced by [`no-empty-character-class`](no-empty-character-class) Categories:❌ 🔧 Fix 💡 Suggestions no-empty-label removed Replaced by [`no-labels`](no-labels) Categories:❌ 🔧 Fix 💡 Suggestions no-extra-strict removed Replaced by [`strict`](strict) Categories:❌ 🔧 Fix 💡 Suggestions no-reserved-keys removed Replaced by [`quote-props`](quote-props) Categories:❌ 🔧 Fix 💡 Suggestions no-space-before-semi removed Replaced by [`semi-spacing`](semi-spacing) Categories:❌ 🔧 Fix 💡 Suggestions no-wrap-func removed Replaced by [`no-extra-parens`](no-extra-parens) Categories:❌ 🔧 Fix 💡 Suggestions space-after-function-name removed Replaced by [`space-before-function-paren`](space-before-function-paren) Categories:❌ 🔧 Fix 💡 Suggestions space-after-keywords removed Replaced by [`keyword-spacing`](keyword-spacing) Categories:❌ 🔧 Fix 💡 Suggestions space-before-function-parentheses removed Replaced by [`space-before-function-paren`](space-before-function-paren) Categories:❌ 🔧 Fix 💡 Suggestions space-before-keywords removed Replaced by [`keyword-spacing`](keyword-spacing) Categories:❌ 🔧 Fix 💡 Suggestions space-in-brackets removed Replaced by [`object-curly-spacing`](object-curly-spacing)[`array-bracket-spacing`](array-bracket-spacing) Categories:❌ 🔧 Fix 💡 Suggestions space-return-throw-case removed Replaced by [`keyword-spacing`](keyword-spacing) Categories:❌ 🔧 Fix 💡 Suggestions space-unary-word-ops removed Replaced by [`space-unary-ops`](space-unary-ops) Categories:❌ 🔧 Fix 💡 Suggestions spaced-line-comment removed Replaced by [`spaced-comment`](spaced-comment) Categories:❌ 🔧 Fix 💡 Suggestions
programming_docs
eslint no-proto no-proto ======== Disallow the use of the `__proto__` property `__proto__` property has been deprecated as of ECMAScript 3.1 and shouldn’t be used in the code. Use `Object.getPrototypeOf` and `Object.setPrototypeOf` instead. Rule Details ------------ When an object is created with the `new` operator, `__proto__` is set to the original “prototype” property of the object’s constructor function. `Object.getPrototypeOf` is the preferred method of getting the object’s prototype. To change an object’s prototype, use `Object.setPrototypeOf`. Examples of **incorrect** code for this rule: ``` /\*eslint no-proto: "error"\*/ var a = obj.__proto__; var a = obj["\_\_proto\_\_"]; obj.__proto__ = b; obj["\_\_proto\_\_"] = b; ``` Examples of **correct** code for this rule: ``` /\*eslint no-proto: "error"\*/ var a = Object.getPrototypeOf(obj); Object.setPrototypeOf(obj, b); var c = { \_\_proto\_\_: a }; ``` When Not To Use It ------------------ You might want to turn this rule off if you need to support legacy browsers which implement the `__proto__` property but not `Object.getPrototypeOf` or `Object.setPrototypeOf`. Version ------- This rule was introduced in ESLint v0.0.9. Further Reading --------------- [John Resig - Object.getPrototypeOf](https://johnresig.com/blog/objectgetprototypeof/) Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/no-proto.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/no-proto.js) eslint no-implied-eval no-implied-eval =============== Disallow the use of `eval()`-like methods It’s considered a good practice to avoid using `eval()` in JavaScript. There are security and performance implications involved with doing so, which is why many linters (including ESLint) recommend disallowing `eval()`. However, there are some other ways to pass a string and have it interpreted as JavaScript code that have similar concerns. The first is using `setTimeout()`, `setInterval()` or `execScript()` (Internet Explorer only), all of which can accept a string of JavaScript code as their first argument. For example: ``` setTimeout("alert('Hi!');", 100); ``` This is considered an implied `eval()` because a string of JavaScript code is passed in to be interpreted. The same can be done with `setInterval()` and `execScript()`. Both interpret the JavaScript code in the global scope. For both `setTimeout()` and `setInterval()`, the first argument can also be a function, and that is considered safer and is more performant: ``` setTimeout(function() { alert("Hi!"); }, 100); ``` The best practice is to always use a function for the first argument of `setTimeout()` and `setInterval()` (and avoid `execScript()`). Rule Details ------------ This rule aims to eliminate implied `eval()` through the use of `setTimeout()`, `setInterval()` or `execScript()`. As such, it will warn when either function is used with a string as the first argument. Examples of **incorrect** code for this rule: ``` /\*eslint no-implied-eval: "error"\*/ setTimeout("alert('Hi!');", 100); setInterval("alert('Hi!');", 100); execScript("alert('Hi!')"); window.setTimeout("count = 5", 10); window.setInterval("foo = bar", 10); ``` Examples of **correct** code for this rule: ``` /\*eslint no-implied-eval: "error"\*/ setTimeout(function() { alert("Hi!"); }, 100); setInterval(function() { alert("Hi!"); }, 100); ``` When Not To Use It ------------------ If you want to allow `setTimeout()` and `setInterval()` with string arguments, then you can safely disable this rule. Related Rules ------------- * <no-eval> Version ------- This rule was introduced in ESLint v0.0.7. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/no-implied-eval.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/no-implied-eval.js) eslint jsx-quotes jsx-quotes ========== Enforce the consistent use of either double or single quotes in JSX attributes 🔧 Fixable Some problems reported by this rule are automatically fixable by the `--fix` [command line](jsx-quotes../user-guide/command-line-interface#--fix) option JSX attribute values can contain string literals, which are delimited with single or double quotes. ``` <a b='c' /> <a b="c" /> ``` Unlike string literals in JavaScript, string literals within JSX attributes can’t contain escaped quotes. If you want to have e.g. a double quote within a JSX attribute value, you have to use single quotes as string delimiter. ``` <a b="'" /> <a b='"' /> ``` Rule Details ------------ This rule enforces the consistent use of either double or single quotes in JSX attributes. Options ------- This rule has a string option: * `"prefer-double"` (default) enforces the use of double quotes for all JSX attribute values that don’t contain a double quote. * `"prefer-single"` enforces the use of single quotes for all JSX attribute values that don’t contain a single quote. ### prefer-double Examples of **incorrect** code for this rule with the default `"prefer-double"` option: ``` /*eslint jsx-quotes: ["error", "prefer-double"]*/ <a b='c' /> ``` Examples of **correct** code for this rule with the default `"prefer-double"` option: ``` /*eslint jsx-quotes: ["error", "prefer-double"]*/ <a b="c" /> <a b='"' /> ``` ### prefer-single Examples of **incorrect** code for this rule with the `"prefer-single"` option: ``` /*eslint jsx-quotes: ["error", "prefer-single"]*/ <a b="c" /> ``` Examples of **correct** code for this rule with the `"prefer-single"` option: ``` /*eslint jsx-quotes: ["error", "prefer-single"]*/ <a b='c' /> <a b="'" /> ``` When Not To Use It ------------------ You can turn this rule off if you don’t use JSX or if you aren’t concerned with a consistent usage of quotes within JSX attributes. Related Rules ------------- * <quotes> Version ------- This rule was introduced in ESLint v1.4.0. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/jsx-quotes.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/jsx-quotes.js) eslint no-restricted-exports no-restricted-exports ===================== Disallow specified names in exports In a project, certain names may be disallowed from being used as exported names for various reasons. Rule Details ------------ This rule disallows specified names from being used as exported names. Options ------- By default, this rule doesn’t disallow any names. Only the names you specify in the configuration will be disallowed. This rule has an object option: * `"restrictedNamedExports"` is an array of strings, where each string is a name to be restricted. Examples of **incorrect** code for this rule: ``` /\*eslint no-restricted-exports: ["error", { "restrictedNamedExports": ["foo", "bar", "Baz", "a", "b", "c", "d", "e", "👍"] }]\*/ export const foo = 1; export function bar() {} export class Baz {} const a = {}; export { a }; function someFunction() {} export { someFunction as b }; export { c } from "some\_module"; export { "d" } from "some\_module"; export { something as e } from "some\_module"; export { "👍" } from "some\_module"; ``` Examples of **correct** code for this rule: ``` /\*eslint no-restricted-exports: ["error", { "restrictedNamedExports": ["foo", "bar", "Baz", "a", "b", "c", "d", "e", "👍"] }]\*/ export const quux = 1; export function myFunction() {} export class MyClass {} const a = {}; export { a as myObject }; function someFunction() {} export { someFunction }; export { c as someName } from "some\_module"; export { "d" as " d " } from "some\_module"; export { something } from "some\_module"; export { "👍" as thumbsUp } from "some\_module"; ``` ### Default exports By design, this rule doesn’t disallow `export default` declarations. If you configure `"default"` as a restricted name, that restriction will apply only to named export declarations. Examples of additional **incorrect** code for this rule: ``` /\*eslint no-restricted-exports: ["error", { "restrictedNamedExports": ["default"] }]\*/ function foo() {} export { foo as default }; ``` ``` /\*eslint no-restricted-exports: ["error", { "restrictedNamedExports": ["default"] }]\*/ export { default } from "some\_module"; ``` Examples of additional **correct** code for this rule: ``` /\*eslint no-restricted-exports: ["error", { "restrictedNamedExports": ["default", "foo"] }]\*/ export default function foo() {} ``` Known Limitations ----------------- This rule doesn’t inspect the content of source modules in re-export declarations. In particular, if you are re-exporting everything from another module’s export, that export may include a restricted name. This rule cannot detect such cases. ``` //----- some\_module.js ----- export function foo() {} //----- my\_module.js ----- /\*eslint no-restricted-exports: ["error", { "restrictedNamedExports": ["foo"] }]\*/ export \* from "some\_module"; // allowed, although this declaration exports "foo" from my\_module ``` Version ------- This rule was introduced in ESLint v7.0.0-alpha.0. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/no-restricted-exports.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/no-restricted-exports.js) eslint comma-style comma-style =========== Enforce consistent comma style 🔧 Fixable Some problems reported by this rule are automatically fixable by the `--fix` [command line](comma-style../user-guide/command-line-interface#--fix) option The Comma Style rule enforces styles for comma-separated lists. There are two comma styles primarily used in JavaScript: * The standard style, in which commas are placed at the end of the current line * Comma First style, in which commas are placed at the start of the next line One of the justifications for using Comma First style is that it can help track missing and trailing commas. These are problematic because missing commas in variable declarations can lead to the leakage of global variables and trailing commas can lead to errors in older versions of IE. Rule Details ------------ This rule enforce consistent comma style in array literals, object literals, and variable declarations. This rule does not apply in either of the following cases: * comma preceded and followed by linebreak (lone comma) * single-line array literals, object literals, and variable declarations Options ------- This rule has a string option: * `"last"` (default) requires a comma after and on the same line as an array element, object property, or variable declaration * `"first"` requires a comma before and on the same line as an array element, object property, or variable declaration This rule also accepts an additional `exceptions` object: * `"exceptions"` has properties whose names correspond to node types in the abstract syntax tree (AST) of JavaScript code: + `"ArrayExpression": true` ignores comma style in array literals + `"ArrayPattern": true` ignores comma style in array patterns of destructuring + `"ArrowFunctionExpression": true` ignores comma style in the parameters of arrow function expressions + `"CallExpression": true` ignores comma style in the arguments of function calls + `"FunctionDeclaration": true` ignores comma style in the parameters of function declarations + `"FunctionExpression": true` ignores comma style in the parameters of function expressions + `"ImportDeclaration": true` ignores comma style in the specifiers of import declarations + `"ObjectExpression": true` ignores comma style in object literals + `"ObjectPattern": true` ignores comma style in object patterns of destructuring + `"VariableDeclaration": true` ignores comma style in variable declarations + `"NewExpression": true` ignores comma style in the parameters of constructor expressions A way to determine the node types as defined by [ESTree](https://github.com/estree/estree) is to use [AST Explorer](https://astexplorer.net/) with the espree parser. ### last Examples of **incorrect** code for this rule with the default `"last"` option: ``` /\*eslint comma-style: ["error", "last"]\*/ var foo = 1 , bar = 2; var foo = 1 , bar = 2; var foo = ["apples" , "oranges"]; function bar() { return { "a": 1 ,"b:": 2 }; } ``` Examples of **correct** code for this rule with the default `"last"` option: ``` /\*eslint comma-style: ["error", "last"]\*/ var foo = 1, bar = 2; var foo = 1, bar = 2; var foo = ["apples", "oranges"]; function bar() { return { "a": 1, "b:": 2 }; } ``` ### first Examples of **incorrect** code for this rule with the `"first"` option: ``` /\*eslint comma-style: ["error", "first"]\*/ var foo = 1, bar = 2; var foo = ["apples", "oranges"]; function bar() { return { "a": 1, "b:": 2 }; } ``` Examples of **correct** code for this rule with the `"first"` option: ``` /\*eslint comma-style: ["error", "first"]\*/ var foo = 1, bar = 2; var foo = 1 ,bar = 2; var foo = ["apples" ,"oranges"]; function bar() { return { "a": 1 ,"b:": 2 }; } ``` ### exceptions An example use case is to enforce comma style *only* in var statements. Examples of **incorrect** code for this rule with sample `"first", { "exceptions": { … } }` options: ``` /\*eslint comma-style: ["error", "first", { "exceptions": { "ArrayExpression": true, "ObjectExpression": true } }]\*/ var o = {}, a = []; ``` Examples of **correct** code for this rule with sample `"first", { "exceptions": { … } }` options: ``` /\*eslint comma-style: ["error", "first", { "exceptions": { "ArrayExpression": true, "ObjectExpression": true } }]\*/ var o = {fst:1, snd: [1, 2]} , a = []; ``` When Not To Use It ------------------ This rule can safely be turned off if your project does not care about enforcing a consistent comma style. Related Rules ------------- * <operator-linebreak> Version ------- This rule was introduced in ESLint v0.9.0. Further Reading --------------- [A better coding convention for lists and object literals in JavaScript](https://gist.github.com/isaacs/357981) Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/comma-style.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/comma-style.js) eslint camelcase camelcase ========= Enforce camelcase naming convention When it comes to naming variables, style guides generally fall into one of two camps: camelcase (`variableName`) and underscores (`variable_name`). This rule focuses on using the camelcase approach. If your style guide calls for camelCasing your variable names, then this rule is for you! Rule Details ------------ This rule looks for any underscores (`_`) located within the source code. It ignores leading and trailing underscores and only checks those in the middle of a variable name. If ESLint decides that the variable is a constant (all uppercase), then no warning will be thrown. Otherwise, a warning will be thrown. This rule only flags definitions and assignments but not function calls. In case of ES6 `import` statements, this rule only targets the name of the variable that will be imported into the local module scope. Options ------- This rule has an object option: * `"properties": "always"` (default) enforces camelcase style for property names * `"properties": "never"` does not check property names * `"ignoreDestructuring": false` (default) enforces camelcase style for destructured identifiers * `"ignoreDestructuring": true` does not check destructured identifiers (but still checks any use of those identifiers later in the code) * `"ignoreImports": false` (default) enforces camelcase style for ES2015 imports * `"ignoreImports": true` does not check ES2015 imports (but still checks any use of the imports later in the code except function arguments) * `"ignoreGlobals": false` (default) enforces camelcase style for global variables * `"ignoreGlobals": true` does not enforce camelcase style for global variables * `allow` (`string[]`) list of properties to accept. Accept regex. ### properties: “always” Examples of **incorrect** code for this rule with the default `{ "properties": "always" }` option: ``` /\*eslint camelcase: "error"\*/ import { no_camelcased } from "external-module" var my_favorite_color = "#112C85"; function do\_something() { // ... } obj.do\_something = function() { // ... }; function foo({ no\_camelcased }) { // ... }; function foo({ isCamelcased: no\_camelcased }) { // ... } function foo({ no_camelcased = 'default value' }) { // ... }; var obj = { my\_pref: 1 }; var { category_id = 1 } = query; var { foo: no_camelcased } = bar; var { foo: bar_baz = 1 } = quz; ``` Examples of **correct** code for this rule with the default `{ "properties": "always" }` option: ``` /\*eslint camelcase: "error"\*/ import { no_camelcased as camelCased } from "external-module"; var myFavoriteColor = "#112C85"; var _myFavoriteColor = "#112C85"; var myFavoriteColor_ = "#112C85"; var MY\_FAVORITE\_COLOR = "#112C85"; var foo = bar.baz_boom; var foo = { qux: bar.baz_boom }; obj.do\_something(); do\_something(); new do\_something(); var { category\_id: category } = query; function foo({ isCamelCased }) { // ... }; function foo({ isCamelCased: isAlsoCamelCased }) { // ... } function foo({ isCamelCased = 'default value' }) { // ... }; var { categoryId = 1 } = query; var { foo: isCamelCased } = bar; var { foo: isCamelCased = 1 } = quz; ``` ### properties: “never” Examples of **correct** code for this rule with the `{ "properties": "never" }` option: ``` /\*eslint camelcase: ["error", {properties: "never"}]\*/ var obj = { my\_pref: 1 }; obj.foo_bar = "baz"; ``` ### ignoreDestructuring: false Examples of **incorrect** code for this rule with the default `{ "ignoreDestructuring": false }` option: ``` /\*eslint camelcase: "error"\*/ var { category_id } = query; var { category_id = 1 } = query; var { category\_id: category_id } = query; var { category\_id: category_alias } = query; var { category\_id: categoryId, ...other_props } = query; ``` ### ignoreDestructuring: true Examples of **incorrect** code for this rule with the `{ "ignoreDestructuring": true }` option: ``` /\*eslint camelcase: ["error", {ignoreDestructuring: true}]\*/ var { category\_id: category_alias } = query; var { category_id, ...other_props } = query; ``` Examples of **correct** code for this rule with the `{ "ignoreDestructuring": true }` option: ``` /\*eslint camelcase: ["error", {ignoreDestructuring: true}]\*/ var { category_id } = query; var { category_id = 1 } = query; var { category\_id: category_id } = query; ``` Please note that this option applies only to identifiers inside destructuring patterns. It doesn’t additionally allow any particular use of the created variables later in the code apart from the use that is already allowed by default or by other options. Examples of additional **incorrect** code for this rule with the `{ "ignoreDestructuring": true }` option: ``` /\*eslint camelcase: ["error", {ignoreDestructuring: true}]\*/ var { some_property } = obj; // allowed by {ignoreDestructuring: true} var foo = some_property + 1; // error, ignoreDestructuring does not apply to this statement ``` A common use case for this option is to avoid useless renaming when the identifier is not intended to be used later in the code. Examples of additional **correct** code for this rule with the `{ "ignoreDestructuring": true }` option: ``` /\*eslint camelcase: ["error", {ignoreDestructuring: true}]\*/ var { some_property, ...rest } = obj; // do something with 'rest', nothing with 'some\_property' ``` Another common use case for this option is in combination with `{ "properties": "never" }`, when the identifier is intended to be used only as a property shorthand. Examples of additional **correct** code for this rule with the `{ "properties": "never", "ignoreDestructuring": true }` options: ``` /\*eslint camelcase: ["error", {"properties": "never", ignoreDestructuring: true}]\*/ var { some_property } = obj; doSomething({ some_property }); ``` ### ignoreImports: false Examples of **incorrect** code for this rule with the default `{ "ignoreImports": false }` option: ``` /\*eslint camelcase: "error"\*/ import { snake_cased } from 'mod'; ``` ### ignoreImports: true Examples of **incorrect** code for this rule with the `{ "ignoreImports": true }` option: ``` /\*eslint camelcase: ["error", {ignoreImports: true}]\*/ import default_import from 'mod'; import \* as namespaced_import from 'mod'; ``` Examples of **correct** code for this rule with the `{ "ignoreImports": true }` option: ``` /\*eslint camelcase: ["error", {ignoreImports: true}]\*/ import { snake_cased } from 'mod'; ``` ### ignoreGlobals: false Examples of **incorrect** code for this rule with the default `{ "ignoreGlobals": false }` option: ``` /\*eslint camelcase: ["error", {ignoreGlobals: false}]\*/ /\* global no\_camelcased \*/ const foo = no_camelcased; ``` ### ignoreGlobals: true Examples of **correct** code for this rule with the `{ "ignoreGlobals": true }` option: ``` /\*eslint camelcase: ["error", {ignoreGlobals: true}]\*/ /\* global no\_camelcased \*/ const foo = no_camelcased; ``` ### allow Examples of **correct** code for this rule with the `allow` option: ``` /\*eslint camelcase: ["error", {allow: ["UNSAFE\_componentWillMount"]}]\*/ function UNSAFE\_componentWillMount() { // ... } ``` ``` /\*eslint camelcase: ["error", {allow: ["^UNSAFE\_"]}]\*/ function UNSAFE\_componentWillMount() { // ... } function UNSAFE\_componentWillMount() { // ... } ``` When Not To Use It ------------------ If you have established coding standards using a different naming convention (separating words with underscores), turn this rule off. Version ------- This rule was introduced in ESLint v0.0.2. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/camelcase.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/camelcase.js)
programming_docs
eslint no-ternary no-ternary ========== Disallow ternary operators The ternary operator is used to conditionally assign a value to a variable. Some believe that the use of ternary operators leads to unclear code. ``` var foo = isBar ? baz : qux; ``` Rule Details ------------ This rule disallows ternary operators. Examples of **incorrect** code for this rule: ``` /\*eslint no-ternary: "error"\*/ var foo = isBar ? baz : qux; function quux() { return foo ? bar() : baz(); } ``` Examples of **correct** code for this rule: ``` /\*eslint no-ternary: "error"\*/ var foo; if (isBar) { foo = baz; } else { foo = qux; } function quux() { if (foo) { return bar(); } else { return baz(); } } ``` Related Rules ------------- * <no-nested-ternary> * <no-unneeded-ternary> Version ------- This rule was introduced in ESLint v0.0.9. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/no-ternary.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/no-ternary.js) eslint no-new-symbol no-new-symbol ============= Disallow `new` operators with the `Symbol` object ✅ Recommended The `"extends": "eslint:recommended"` property in a [configuration file](no-new-symbol../user-guide/configuring/configuration-files#extending-configuration-files) enables this rule `Symbol` is not intended to be used with the `new` operator, but to be called as a function. ``` var foo = new Symbol("foo"); ``` This throws a `TypeError` exception. Rule Details ------------ This rule is aimed at preventing the accidental calling of `Symbol` with the `new` operator. Examples -------- Examples of **incorrect** code for this rule: ``` /\*eslint no-new-symbol: "error"\*/ /\*eslint-env es6\*/ var foo = new Symbol('foo'); ``` Examples of **correct** code for this rule: ``` /\*eslint no-new-symbol: "error"\*/ /\*eslint-env es6\*/ var foo = Symbol('foo'); // Ignores shadowed Symbol. function bar(Symbol) { const baz = new Symbol("baz"); } ``` When Not To Use It ------------------ This rule should not be used in ES3/5 environments. Version ------- This rule was introduced in ESLint v2.0.0-beta.1. Further Reading --------------- [ECMAScript 2015 Language Specification – ECMA-262 6th Edition](https://www.ecma-international.org/ecma-262/6.0/#sec-symbol-objects) Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/no-new-symbol.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/no-new-symbol.js) eslint one-var one-var ======= Enforce variables to be declared either together or separately in functions 🔧 Fixable Some problems reported by this rule are automatically fixable by the `--fix` [command line](one-var../user-guide/command-line-interface#--fix) option Variables can be declared at any point in JavaScript code using `var`, `let`, or `const`. There are many styles and preferences related to the declaration of variables, and one of those is deciding on how many variable declarations should be allowed in a single function. There are two schools of thought in this regard: 1. There should be just one variable declaration for all variables in the function. That declaration typically appears at the top of the function. 2. You should use one variable declaration for each variable you want to define. For instance: ``` // one variable declaration per function function foo() { var bar, baz; } // multiple variable declarations per function function foo() { var bar; var baz; } ``` The single-declaration school of thought is based in pre-ECMAScript 6 behaviors, where there was no such thing as block scope, only function scope. Since all `var` statements are hoisted to the top of the function anyway, some believe that declaring all variables in a single declaration at the top of the function removes confusion around scoping rules. Rule Details ------------ This rule enforces variables to be declared either together or separately per function ( for `var`) or block (for `let` and `const`) scope. Options ------- This rule has one option, which can be a string option or an object option. String option: * `"always"` (default) requires one variable declaration per scope * `"never"` requires multiple variable declarations per scope * `"consecutive"` allows multiple variable declarations per scope but requires consecutive variable declarations to be combined into a single declaration Object option: * `"var": "always"` requires one `var` declaration per function * `"var": "never"` requires multiple `var` declarations per function * `"var": "consecutive"` requires consecutive `var` declarations to be a single declaration * `"let": "always"` requires one `let` declaration per block * `"let": "never"` requires multiple `let` declarations per block * `"let": "consecutive"` requires consecutive `let` declarations to be a single declaration * `"const": "always"` requires one `const` declaration per block * `"const": "never"` requires multiple `const` declarations per block * `"const": "consecutive"` requires consecutive `const` declarations to be a single declaration * `"separateRequires": true` enforces `requires` to be separate from declarations Alternate object option: * `"initialized": "always"` requires one variable declaration for initialized variables per scope * `"initialized": "never"` requires multiple variable declarations for initialized variables per scope * `"initialized": "consecutive"` requires consecutive variable declarations for initialized variables to be a single declaration * `"uninitialized": "always"` requires one variable declaration for uninitialized variables per scope * `"uninitialized": "never"` requires multiple variable declarations for uninitialized variables per scope * `"uninitialized": "consecutive"` requires consecutive variable declarations for uninitialized variables to be a single declaration ### always Examples of **incorrect** code for this rule with the default `"always"` option: ``` /\*eslint one-var: ["error", "always"]\*/ function foo() { var bar; var baz; let qux; let norf; } function foo(){ const bar = false; const baz = true; let qux; let norf; } function foo() { var bar; if (baz) { var qux = true; } } class C { static { var foo; var bar; } static { var foo; if (bar) { var baz = true; } } static { let foo; let bar; } } ``` Examples of **correct** code for this rule with the default `"always"` option: ``` /\*eslint one-var: ["error", "always"]\*/ function foo() { var bar, baz; let qux, norf; } function foo(){ const bar = true, baz = false; let qux, norf; } function foo() { var bar, qux; if (baz) { qux = true; } } function foo(){ let bar; if (baz) { let qux; } } class C { static { var foo, bar; } static { var foo, baz; if (bar) { baz = true; } } static { let foo, bar; } static { let foo; if (bar) { let baz; } } } ``` ### never Examples of **incorrect** code for this rule with the `"never"` option: ``` /\*eslint one-var: ["error", "never"]\*/ function foo() { var bar, baz; const bar = true, baz = false; } function foo() { var bar, qux; if (baz) { qux = true; } } function foo(){ let bar = true, baz = false; } class C { static { var foo, bar; let baz, qux; } } ``` Examples of **correct** code for this rule with the `"never"` option: ``` /\*eslint one-var: ["error", "never"]\*/ function foo() { var bar; var baz; } function foo() { var bar; if (baz) { var qux = true; } } function foo() { let bar; if (baz) { let qux = true; } } class C { static { var foo; var bar; let baz; let qux; } } // declarations with multiple variables are allowed in for-loop initializers for (var i = 0, len = arr.length; i < len; i++) { doSomething(arr[i]); } ``` ### consecutive Examples of **incorrect** code for this rule with the `"consecutive"` option: ``` /\*eslint one-var: ["error", "consecutive"]\*/ function foo() { var bar; var baz; } function foo(){ var bar = 1; var baz = 2; qux(); var qux = 3; var quux; } class C { static { var foo; var bar; let baz; let qux; } } ``` Examples of **correct** code for this rule with the `"consecutive"` option: ``` /\*eslint one-var: ["error", "consecutive"]\*/ function foo() { var bar, baz; } function foo(){ var bar = 1, baz = 2; qux(); var qux = 3, quux; } class C { static { var foo, bar; let baz, qux; doSomething(); let quux; var quuux; } } ``` ### var, let, and const Examples of **incorrect** code for this rule with the `{ var: "always", let: "never", const: "never" }` option: ``` /\*eslint one-var: ["error", { var: "always", let: "never", const: "never" }]\*/ /\*eslint-env es6\*/ function foo() { var bar; var baz; let qux, norf; } function foo() { const bar = 1, baz = 2; let qux, norf; } ``` Examples of **correct** code for this rule with the `{ var: "always", let: "never", const: "never" }` option: ``` /\*eslint one-var: ["error", { var: "always", let: "never", const: "never" }]\*/ /\*eslint-env es6\*/ function foo() { var bar, baz; let qux; let norf; } function foo() { const bar = 1; const baz = 2; let qux; let norf; } ``` Examples of **incorrect** code for this rule with the `{ var: "never" }` option: ``` /\*eslint one-var: ["error", { var: "never" }]\*/ /\*eslint-env es6\*/ function foo() { var bar, baz; } ``` Examples of **correct** code for this rule with the `{ var: "never" }` option: ``` /\*eslint one-var: ["error", { var: "never" }]\*/ /\*eslint-env es6\*/ function foo() { var bar, baz; const bar = 1; // `const` and `let` declarations are ignored if they are not specified const baz = 2; let qux; let norf; } ``` Examples of **incorrect** code for this rule with the `{ separateRequires: true }` option: ``` /\*eslint one-var: ["error", { separateRequires: true, var: "always" }]\*/ /\*eslint-env node\*/ var foo = require("foo"), bar = "bar"; ``` Examples of **correct** code for this rule with the `{ separateRequires: true }` option: ``` /\*eslint one-var: ["error", { separateRequires: true, var: "always" }]\*/ /\*eslint-env node\*/ var foo = require("foo"); var bar = "bar"; ``` ``` var foo = require("foo"), bar = require("bar"); ``` Examples of **incorrect** code for this rule with the `{ var: "never", let: "consecutive", const: "consecutive" }` option: ``` /\*eslint one-var: ["error", { var: "never", let: "consecutive", const: "consecutive" }]\*/ /\*eslint-env es6\*/ function foo() { let a, b; let c; var d, e; } function foo() { const a = 1, b = 2; const c = 3; var d, e; } ``` Examples of **correct** code for this rule with the `{ var: "never", let: "consecutive", const: "consecutive" }` option: ``` /\*eslint one-var: ["error", { var: "never", let: "consecutive", const: "consecutive" }]\*/ /\*eslint-env es6\*/ function foo() { let a, b; var d; var e; let f; } function foo() { const a = 1, b = 2; var c; var d; const e = 3; } ``` Examples of **incorrect** code for this rule with the `{ var: "consecutive" }` option: ``` /\*eslint one-var: ["error", { var: "consecutive" }]\*/ /\*eslint-env es6\*/ function foo() { var a; var b; } ``` Examples of **correct** code for this rule with the `{ var: "consecutive" }` option: ``` /\*eslint one-var: ["error", { var: "consecutive" }]\*/ /\*eslint-env es6\*/ function foo() { var a, b; const c = 1; // `const` and `let` declarations are ignored if they are not specified const d = 2; let e; let f; } ``` ### initialized and uninitialized Examples of **incorrect** code for this rule with the `{ "initialized": "always", "uninitialized": "never" }` option: ``` /\*eslint one-var: ["error", { "initialized": "always", "uninitialized": "never" }]\*/ /\*eslint-env es6\*/ function foo() { var a, b, c; var foo = true; var bar = false; } ``` Examples of **correct** code for this rule with the `{ "initialized": "always", "uninitialized": "never" }` option: ``` /\*eslint one-var: ["error", { "initialized": "always", "uninitialized": "never" }]\*/ function foo() { var a; var b; var c; var foo = true, bar = false; } for (let z of foo) { doSomething(z); } let z; for (z of foo) { doSomething(z); } ``` Examples of **incorrect** code for this rule with the `{ "initialized": "never" }` option: ``` /\*eslint one-var: ["error", { "initialized": "never" }]\*/ /\*eslint-env es6\*/ function foo() { var foo = true, bar = false; } ``` Examples of **correct** code for this rule with the `{ "initialized": "never" }` option: ``` /\*eslint one-var: ["error", { "initialized": "never" }]\*/ function foo() { var foo = true; var bar = false; var a, b, c; // Uninitialized variables are ignored } ``` Examples of **incorrect** code for this rule with the `{ "initialized": "consecutive", "uninitialized": "never" }` option: ``` /\*eslint one-var: ["error", { "initialized": "consecutive", "uninitialized": "never" }]\*/ function foo() { var a = 1; var b = 2; var c, d; var e = 3; var f = 4; } ``` Examples of **correct** code for this rule with the `{ "initialized": "consecutive", "uninitialized": "never" }` option: ``` /\*eslint one-var: ["error", { "initialized": "consecutive", "uninitialized": "never" }]\*/ function foo() { var a = 1, b = 2; var c; var d; var e = 3, f = 4; } ``` Examples of **incorrect** code for this rule with the `{ "initialized": "consecutive" }` option: ``` /\*eslint one-var: ["error", { "initialized": "consecutive" }]\*/ function foo() { var a = 1; var b = 2; foo(); var c = 3; var d = 4; } ``` Examples of **correct** code for this rule with the `{ "initialized": "consecutive" }` option: ``` /\*eslint one-var: ["error", { "initialized": "consecutive" }]\*/ function foo() { var a = 1, b = 2; foo(); var c = 3, d = 4; } ``` Compatibility ------------- * **JSHint**: This rule maps to the `onevar` JSHint rule, but allows `let` and `const` to be configured separately. * **JSCS**: This rule roughly maps to [disallowMultipleVarDecl](https://jscs-dev.github.io/rule/disallowMultipleVarDecl). * **JSCS**: This rule option `separateRequires` roughly maps to [requireMultipleVarDecl](https://jscs-dev.github.io/rule/requireMultipleVarDecl). Version ------- This rule was introduced in ESLint v0.0.9. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/one-var.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/one-var.js) eslint template-curly-spacing template-curly-spacing ====================== Require or disallow spacing around embedded expressions of template strings 🔧 Fixable Some problems reported by this rule are automatically fixable by the `--fix` [command line](template-curly-spacing../user-guide/command-line-interface#--fix) option We can embed expressions in template strings with using a pair of `${` and `}`. This rule can force usage of spacing *within* the curly brace pair according to style guides. ``` let hello = `hello, ${people.name}!`; ``` Rule Details ------------ This rule aims to maintain consistency around the spacing inside of template literals. Options ------- ``` { "template-curly-spacing": ["error", "never"] } ``` This rule has one option which has either `"never"` or `"always"` as value. * `"never"` (by default) - Disallows spaces inside of the curly brace pair. * `"always"` - Requires one or more spaces inside of the curly brace pair. Examples -------- ### never Examples of **incorrect** code for this rule with the default `"never"` option: ``` /\*eslint template-curly-spacing: "error"\*/ `hello, ${ people.name}!`; `hello, ${people.name }!`; `hello, ${ people.name }!`; ``` Examples of **correct** code for this rule with the default `"never"` option: ``` /\*eslint template-curly-spacing: "error"\*/ `hello, ${people.name}!`; `hello, ${ people.name }!`; ``` ### always Examples of **incorrect** code for this rule with the `"always"` option: ``` /\*eslint template-curly-spacing: ["error", "always"]\*/ `hello, ${ people.name}!`; `hello, ${people.name }!`; `hello, ${people.name}!`; ``` Examples of **correct** code for this rule with the `"always"` option: ``` /\*eslint template-curly-spacing: ["error", "always"]\*/ `hello, ${ people.name }!`; `hello, ${ people.name }!`; ``` When Not To Use It ------------------ If you don’t want to be notified about usage of spacing inside of template strings, then it’s safe to disable this rule. Version ------- This rule was introduced in ESLint v2.0.0-rc.0. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/template-curly-spacing.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/template-curly-spacing.js) eslint no-spaced-func no-spaced-func ============== Disallow spacing between function identifiers and their applications (deprecated) 🔧 Fixable Some problems reported by this rule are automatically fixable by the `--fix` [command line](no-spaced-func../user-guide/command-line-interface#--fix) option This rule was **deprecated** in ESLint v3.3.0 and replaced by the [func-call-spacing](no-spaced-funcfunc-call-spacing) rule. While it’s possible to have whitespace between the name of a function and the parentheses that execute it, such patterns tend to look more like errors. Rule Details ------------ This rule disallows spacing between function identifiers and their applications. Examples of **incorrect** code for this rule: ``` /\*eslint no-spaced-func: "error"\*/ fn () fn () ``` Examples of **correct** code for this rule: ``` /\*eslint no-spaced-func: "error"\*/ fn() ``` Version ------- This rule was introduced in ESLint v0.1.2. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/no-spaced-func.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/no-spaced-func.js) eslint curly curly ===== Enforce consistent brace style for all control statements 🔧 Fixable Some problems reported by this rule are automatically fixable by the `--fix` [command line](curly../user-guide/command-line-interface#--fix) option JavaScript allows the omission of curly braces when a block contains only one statement. However, it is considered by many to be best practice to *never* omit curly braces around blocks, even when they are optional, because it can lead to bugs and reduces code clarity. So the following: ``` if (foo) foo++; ``` Can be rewritten as: ``` if (foo) { foo++; } ``` There are, however, some who prefer to only use braces when there is more than one statement to be executed. Rule Details ------------ This rule is aimed at preventing bugs and increasing code clarity by ensuring that block statements are wrapped in curly braces. It will warn when it encounters blocks that omit curly braces. Options ------- ### all Examples of **incorrect** code for the default `"all"` option: ``` /\*eslint curly: "error"\*/ if (foo) foo++; while (bar) baz(); if (foo) { baz(); } else qux(); ``` Examples of **correct** code for the default `"all"` option: ``` /\*eslint curly: "error"\*/ if (foo) { foo++; } while (bar) { baz(); } if (foo) { baz(); } else { qux(); } ``` ### multi By default, this rule warns whenever `if`, `else`, `for`, `while`, or `do` are used without block statements as their body. However, you can specify that block statements should be used only when there are multiple statements in the block and warn when there is only one statement in the block. Examples of **incorrect** code for the `"multi"` option: ``` /\*eslint curly: ["error", "multi"]\*/ if (foo) { foo++; } if (foo) bar(); else { foo++; } while (true) { doSomething(); } for (var i=0; i < items.length; i++) { doSomething(); } ``` Examples of **correct** code for the `"multi"` option: ``` /\*eslint curly: ["error", "multi"]\*/ if (foo) foo++; else foo(); while (true) { doSomething(); doSomethingElse(); } ``` ### multi-line Alternatively, you can relax the rule to allow brace-less single-line `if`, `else if`, `else`, `for`, `while`, or `do`, while still enforcing the use of curly braces for other instances. Examples of **incorrect** code for the `"multi-line"` option: ``` /\*eslint curly: ["error", "multi-line"]\*/ if (foo) doSomething(); else doSomethingElse(); if (foo) foo( bar, baz); ``` Examples of **correct** code for the `"multi-line"` option: ``` /\*eslint curly: ["error", "multi-line"]\*/ if (foo) foo++; else doSomething(); if (foo) foo++; else if (bar) baz() else doSomething(); do something(); while (foo); while (foo && bar) baz(); if (foo) { foo++; } if (foo) { foo++; } while (true) { doSomething(); doSomethingElse(); } ``` ### multi-or-nest You can use another configuration that forces brace-less `if`, `else if`, `else`, `for`, `while`, or `do` if their body contains only one single-line statement. And forces braces in all other cases. Examples of **incorrect** code for the `"multi-or-nest"` option: ``` /\*eslint curly: ["error", "multi-or-nest"]\*/ if (!foo) foo = { bar: baz, qux: foo }; while (true) if(foo) doSomething(); else doSomethingElse(); if (foo) { foo++; } while (true) { doSomething(); } for (var i = 0; foo; i++) { doSomething(); } ``` Examples of **correct** code for the `"multi-or-nest"` option: ``` /\*eslint curly: ["error", "multi-or-nest"]\*/ if (!foo) { foo = { bar: baz, qux: foo }; } while (true) { if(foo) doSomething(); else doSomethingElse(); } if (foo) foo++; while (true) doSomething(); for (var i = 0; foo; i++) doSomething(); ``` For single-line statements preceded by a comment, braces are allowed but not required. Examples of additional **correct** code for the `"multi-or-nest"` option: ``` /\*eslint curly: ["error", "multi-or-nest"]\*/ if (foo) // some comment bar(); if (foo) { // some comment bar(); } ``` ### consistent When using any of the `multi*` options, you can add an option to enforce all bodies of a `if`, `else if` and `else` chain to be with or without braces. Examples of **incorrect** code for the `"multi", "consistent"` options: ``` /\*eslint curly: ["error", "multi", "consistent"]\*/ if (foo) { bar(); baz(); } else buz(); if (foo) bar(); else if (faa) bor(); else { other(); things(); } if (true) foo(); else { baz(); } if (foo) { foo++; } ``` Examples of **correct** code for the `"multi", "consistent"` options: ``` /\*eslint curly: ["error", "multi", "consistent"]\*/ if (foo) { bar(); baz(); } else { buz(); } if (foo) { bar(); } else if (faa) { bor(); } else { other(); things(); } if (true) foo(); else baz(); if (foo) foo++; ``` When Not To Use It ------------------ If you have no strict conventions about when to use block statements and when not to, you can safely disable this rule. Version ------- This rule was introduced in ESLint v0.0.2. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/curly.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/curly.js)
programming_docs
eslint newline-per-chained-call newline-per-chained-call ======================== Require a newline after each call in a method chain 🔧 Fixable Some problems reported by this rule are automatically fixable by the `--fix` [command line](newline-per-chained-call../user-guide/command-line-interface#--fix) option Chained method calls on a single line without line breaks are harder to read, so some developers place a newline character after each method call in the chain to make it more readable and easy to maintain. Let’s look at the following perfectly valid (but single line) code. ``` d3.select("body").selectAll("p").data([4, 8, 15, 16, 23, 42 ]).enter().append("p").text(function(d) { return "I'm number " + d + "!"; }); ``` However, with appropriate new lines, it becomes easy to read and understand. Look at the same code written below with line breaks after each call. ``` d3 .select("body") .selectAll("p") .data([ 4, 8, 15, 16, 23, 42 ]) .enter() .append("p") .text(function (d) { return "I'm number " + d + "!"; }); ``` Another argument in favor of this style is that it improves the clarity of diffs when something in the method chain is changed: Less clear: ``` -d3.select("body").selectAll("p").style("color", "white"); +d3.select("body").selectAll("p").style("color", "blue"); ``` More clear: ``` d3 .select("body") .selectAll("p") - .style("color", "white"); + .style("color", "blue"); ``` Rule Details ------------ This rule requires a newline after each call in a method chain or deep member access. Computed property accesses such as `instance[something]` are excluded. Options ------- This rule has an object option: * `"ignoreChainWithDepth"` (default: `2`) allows chains up to a specified depth. ### ignoreChainWithDepth Examples of **incorrect** code for this rule with the default `{ "ignoreChainWithDepth": 2 }` option: ``` /\*eslint newline-per-chained-call: ["error", { "ignoreChainWithDepth": 2 }]\*/ _.chain({}).map(foo).filter(bar).value(); // Or _.chain({}).map(foo).filter(bar); // Or _ .chain({}).map(foo) .filter(bar); // Or obj.method().method2().method3(); ``` Examples of **correct** code for this rule with the default `{ "ignoreChainWithDepth": 2 }` option: ``` /\*eslint newline-per-chained-call: ["error", { "ignoreChainWithDepth": 2 }]\*/ _ .chain({}) .map(foo) .filter(bar) .value(); // Or _ .chain({}) .map(foo) .filter(bar); // Or _.chain({}) .map(foo) .filter(bar); // Or obj .prop .method().prop; // Or obj .prop.method() .method2() .method3().prop; ``` When Not To Use It ------------------ If you have conflicting rules or when you are fine with chained calls on one line, you can safely turn this rule off. Version ------- This rule was introduced in ESLint v2.0.0-rc.0. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/newline-per-chained-call.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/newline-per-chained-call.js) eslint arrow-spacing arrow-spacing ============= Enforce consistent spacing before and after the arrow in arrow functions 🔧 Fixable Some problems reported by this rule are automatically fixable by the `--fix` [command line](arrow-spacing../user-guide/command-line-interface#--fix) option This rule normalize style of spacing before/after an arrow function’s arrow(`=>`). ``` /\*eslint-env es6\*/ // { "before": true, "after": true } (a) => {} // { "before": false, "after": false } (a)=>{} ``` Rule Details ------------ This rule takes an object argument with `before` and `after` properties, each with a Boolean value. The default configuration is `{ "before": true, "after": true }`. `true` means there should be **one or more spaces** and `false` means **no spaces**. Examples of **incorrect** code for this rule with the default `{ "before": true, "after": true }` option: ``` /\*eslint arrow-spacing: "error"\*/ /\*eslint-env es6\*/ ()=> {}; () =>{}; (a)=> {}; (a) =>{}; a =>a; a=> a; ()=> {'\n'}; () =>{'\n'}; ``` Examples of **correct** code for this rule with the default `{ "before": true, "after": true }` option: ``` /\*eslint arrow-spacing: "error"\*/ /\*eslint-env es6\*/ () => {}; (a) => {}; a => a; () => {'\n'}; ``` Examples of **incorrect** code for this rule with the `{ "before": false, "after": false }` option: ``` /\*eslint arrow-spacing: ["error", { "before": false, "after": false }]\*/ /\*eslint-env es6\*/ () =>{}; (a) => {}; ()=> {'\n'}; ``` Examples of **correct** code for this rule with the `{ "before": false, "after": false }` option: ``` /\*eslint arrow-spacing: ["error", { "before": false, "after": false }]\*/ /\*eslint-env es6\*/ ()=>{}; (a)=>{}; ()=>{'\n'}; ``` Examples of **incorrect** code for this rule with the `{ "before": false, "after": true }` option: ``` /\*eslint arrow-spacing: ["error", { "before": false, "after": true }]\*/ /\*eslint-env es6\*/ () =>{}; (a) => {}; ()=>{'\n'}; ``` Examples of **correct** code for this rule with the `{ "before": false, "after": true }` option: ``` /\*eslint arrow-spacing: ["error", { "before": false, "after": true }]\*/ /\*eslint-env es6\*/ ()=> {}; (a)=> {}; ()=> {'\n'}; ``` Version ------- This rule was introduced in ESLint v1.0.0-rc-1. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/arrow-spacing.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/arrow-spacing.js) eslint no-empty-pattern no-empty-pattern ================ Disallow empty destructuring patterns ✅ Recommended The `"extends": "eslint:recommended"` property in a [configuration file](no-empty-pattern../user-guide/configuring/configuration-files#extending-configuration-files) enables this rule When using destructuring, it’s possible to create a pattern that has no effect. This happens when empty curly braces are used to the right of an embedded object destructuring pattern, such as: ``` // doesn't create any variables var {a: {}} = foo; ``` In this code, no new variables are created because `a` is just a location helper while the `{}` is expected to contain the variables to create, such as: ``` // creates variable b var {a: { b }} = foo; ``` In many cases, the empty object pattern is a mistake where the author intended to use a default value instead, such as: ``` // creates variable a var {a = {}} = foo; ``` The difference between these two patterns is subtle, especially because the problematic empty pattern looks just like an object literal. Rule Details ------------ This rule aims to flag any empty patterns in destructured objects and arrays, and as such, will report a problem whenever one is encountered. Examples of **incorrect** code for this rule: ``` /\*eslint no-empty-pattern: "error"\*/ var {} = foo; var [] = foo; var {a: {}} = foo; var {a: []} = foo; function foo({}) {} function foo([]) {} function foo({a: {}}) {} function foo({a: []}) {} ``` Examples of **correct** code for this rule: ``` /\*eslint no-empty-pattern: "error"\*/ var {a = {}} = foo; var {a = []} = foo; function foo({a = {}}) {} function foo({a = []}) {} ``` Version ------- This rule was introduced in ESLint v1.7.0. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/no-empty-pattern.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/no-empty-pattern.js) eslint no-shadow no-shadow ========= Disallow variable declarations from shadowing variables declared in the outer scope Shadowing is the process by which a local variable shares the same name as a variable in its containing scope. For example: ``` var a = 3; function b() { var a = 10; } ``` In this case, the variable `a` inside of `b()` is shadowing the variable `a` in the global scope. This can cause confusion while reading the code and it’s impossible to access the global variable. Rule Details ------------ This rule aims to eliminate shadowed variable declarations. Examples of **incorrect** code for this rule: ``` /\*eslint no-shadow: "error"\*/ /\*eslint-env es6\*/ var a = 3; function b() { var a = 10; } var b = function () { var a = 10; } function b(a) { a = 10; } b(a); if (true) { let a = 5; } ``` Options ------- This rule takes one option, an object, with properties `"builtinGlobals"`, `"hoist"`, `"allow"` and `"ignoreOnInitialization"`. ``` { "no-shadow": ["error", { "builtinGlobals": false, "hoist": "functions", "allow": [], "ignoreOnInitialization": false }] } ``` ### builtinGlobals The `builtinGlobals` option is `false` by default. If it is `true`, the rule prevents shadowing of built-in global variables: `Object`, `Array`, `Number`, and so on. Examples of **incorrect** code for the `{ "builtinGlobals": true }` option: ``` /\*eslint no-shadow: ["error", { "builtinGlobals": true }]\*/ function foo() { var Object = 0; } ``` ### hoist The `hoist` option has three settings: * `functions` (by default) - reports shadowing before the outer functions are defined. * `all` - reports all shadowing before the outer variables/functions are defined. * `never` - never report shadowing before the outer variables/functions are defined. #### hoist: functions Examples of **incorrect** code for the default `{ "hoist": "functions" }` option: ``` /\*eslint no-shadow: ["error", { "hoist": "functions" }]\*/ /\*eslint-env es6\*/ if (true) { let b = 6; } function b() {} ``` Although `let b` in the `if` statement is before the *function* declaration in the outer scope, it is incorrect. Examples of **correct** code for the default `{ "hoist": "functions" }` option: ``` /\*eslint no-shadow: ["error", { "hoist": "functions" }]\*/ /\*eslint-env es6\*/ if (true) { let a = 3; } let a = 5; ``` Because `let a` in the `if` statement is before the *variable* declaration in the outer scope, it is correct. #### hoist: all Examples of **incorrect** code for the `{ "hoist": "all" }` option: ``` /\*eslint no-shadow: ["error", { "hoist": "all" }]\*/ /\*eslint-env es6\*/ if (true) { let a = 3; let b = 6; } let a = 5; function b() {} ``` #### hoist: never Examples of **correct** code for the `{ "hoist": "never" }` option: ``` /\*eslint no-shadow: ["error", { "hoist": "never" }]\*/ /\*eslint-env es6\*/ if (true) { let a = 3; let b = 6; } let a = 5; function b() {} ``` Because `let a` and `let b` in the `if` statement are before the declarations in the outer scope, they are correct. ### allow The `allow` option is an array of identifier names for which shadowing is allowed. For example, `"resolve"`, `"reject"`, `"done"`, `"cb"`. Examples of **correct** code for the `{ "allow": ["done"] }` option: ``` /\*eslint no-shadow: ["error", { "allow": ["done"] }]\*/ /\*eslint-env es6\*/ import async from 'async'; function foo(done) { async.map([1, 2], function (e, done) { done(null, e \* 2) }, done); } foo(function (err, result) { console.log({ err, result }); }); ``` ### ignoreOnInitialization The `ignoreOnInitialization` option is `false` by default. If it is `true`, it prevents reporting shadowing of variables in their initializers when the shadowed variable is presumably still uninitialized. The shadowed variable must be on the left side. The shadowing variable must be on the right side and declared in a callback function or in an IIFE. Examples of **incorrect** code for the `{ "ignoreOnInitialization": "true" }` option: ``` /\*eslint no-shadow: ["error", { "ignoreOnInitialization": true }]\*/ var x = x => x; ``` Because the shadowing variable `x` will shadow the already initialized shadowed variable `x`. Examples of **correct** code for the `{ "ignoreOnInitialization": true }` option: ``` /\*eslint no-shadow: ["error", { "ignoreOnInitialization": true }]\*/ var x = foo(x => x) var y = (y => y)() ``` The rationale for callback functions is the assumption that they will be called during the initialization, so that at the time when the shadowing variable will be used, the shadowed variable has not yet been initialized. Related Rules ------------- * <no-shadow-restricted-names> Version ------- This rule was introduced in ESLint v0.0.9. Further Reading --------------- [Variable shadowing - Wikipedia](https://en.wikipedia.org/wiki/Variable_shadowing) Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/no-shadow.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/no-shadow.js) eslint dot-location dot-location ============ Enforce consistent newlines before and after dots 🔧 Fixable Some problems reported by this rule are automatically fixable by the `--fix` [command line](dot-location../user-guide/command-line-interface#--fix) option JavaScript allows you to place newlines before or after a dot in a member expression. Consistency in placing a newline before or after the dot can greatly increase readability. ``` var a = universe. galaxy; var b = universe .galaxy; ``` Rule Details ------------ This rule aims to enforce newline consistency in member expressions. This rule prevents the use of mixed newlines around the dot in a member expression. Options ------- The rule takes one option, a string: * If it is `"object"` (default), the dot in a member expression should be on the same line as the object portion. * If it is `"property"`, the dot in a member expression should be on the same line as the property portion. ### object The default `"object"` option requires the dot to be on the same line as the object. Examples of **incorrect** code for the default `"object"` option: ``` /\*eslint dot-location: ["error", "object"]\*/ var foo = object .property; ``` Examples of **correct** code for the default `"object"` option: ``` /\*eslint dot-location: ["error", "object"]\*/ var foo = object. property; var bar = ( object ). property; var baz = object.property; ``` ### property The `"property"` option requires the dot to be on the same line as the property. Examples of **incorrect** code for the `"property"` option: ``` /\*eslint dot-location: ["error", "property"]\*/ var foo = object. property; ``` Examples of **correct** code for the `"property"` option: ``` /\*eslint dot-location: ["error", "property"]\*/ var foo = object .property; var bar = object.property; ``` When Not To Use It ------------------ You can turn this rule off if you are not concerned with the consistency of newlines before or after dots in member expressions. Related Rules ------------- * <newline-after-var> * <dot-notation> Version ------- This rule was introduced in ESLint v0.21.0. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/dot-location.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/dot-location.js) eslint valid-typeof valid-typeof ============ Enforce comparing `typeof` expressions against valid strings ✅ Recommended The `"extends": "eslint:recommended"` property in a [configuration file](valid-typeof../user-guide/configuring/configuration-files#extending-configuration-files) enables this rule 💡 hasSuggestions Some problems reported by this rule are manually fixable by editor [suggestions](valid-typeof../developer-guide/working-with-rules#providing-suggestions) For a vast majority of use cases, the result of the `typeof` operator is one of the following string literals: `"undefined"`, `"object"`, `"boolean"`, `"number"`, `"string"`, `"function"`, `"symbol"`, and `"bigint"`. It is usually a typing mistake to compare the result of a `typeof` operator to other string literals. Rule Details ------------ This rule enforces comparing `typeof` expressions to valid string literals. Options ------- This rule has an object option: * `"requireStringLiterals": true` requires `typeof` expressions to only be compared to string literals or other `typeof` expressions, and disallows comparisons to any other value. Examples of **incorrect** code for this rule: ``` /\*eslint valid-typeof: "error"\*/ typeof foo === "strnig" typeof foo == "undefimed" typeof bar != "nunber" typeof bar !== "fucntion" ``` Examples of **correct** code for this rule: ``` /\*eslint valid-typeof: "error"\*/ typeof foo === "string" typeof bar == "undefined" typeof foo === baz typeof bar === typeof qux ``` Examples of **incorrect** code with the `{ "requireStringLiterals": true }` option: ``` /\*eslint valid-typeof: ["error", { "requireStringLiterals": true }]\*/ typeof foo === undefined typeof bar == Object typeof baz === "strnig" typeof qux === "some invalid type" typeof baz === anotherVariable typeof foo == 5 ``` Examples of **correct** code with the `{ "requireStringLiterals": true }` option: ``` /\*eslint valid-typeof: ["error", { "requireStringLiterals": true }]\*/ typeof foo === "undefined" typeof bar == "object" typeof baz === "string" typeof bar === typeof qux ``` When Not To Use It ------------------ You may want to turn this rule off if you will be using the `typeof` operator on host objects. Version ------- This rule was introduced in ESLint v0.5.0. Further Reading --------------- [typeof - JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof) Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/valid-typeof.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/valid-typeof.js) eslint prefer-exponentiation-operator prefer-exponentiation-operator ============================== Disallow the use of `Math.pow` in favor of the `**` operator 🔧 Fixable Some problems reported by this rule are automatically fixable by the `--fix` [command line](prefer-exponentiation-operator../user-guide/command-line-interface#--fix) option Introduced in ES2016, the infix exponentiation operator `**` is an alternative for the standard `Math.pow` function. Infix notation is considered to be more readable and thus more preferable than the function notation. Rule Details ------------ This rule disallows calls to `Math.pow` and suggests using the `**` operator instead. Examples of **incorrect** code for this rule: ``` /\*eslint prefer-exponentiation-operator: "error"\*/ const foo = Math.pow(2, 8); const bar = Math.pow(a, b); let baz = Math.pow(a + b, c + d); let quux = Math.pow(-1, n); ``` Examples of **correct** code for this rule: ``` /\*eslint prefer-exponentiation-operator: "error"\*/ const foo = 2 \*\* 8; const bar = a \*\* b; let baz = (a + b) \*\* (c + d); let quux = (-1) \*\* n; ``` When Not To Use It ------------------ This rule should not be used unless ES2016 is supported in your codebase. Version ------- This rule was introduced in ESLint v6.7.0. Further Reading --------------- [Exponentiation (\*\*) - JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Exponentiation) [5848 - v8 - V8 JavaScript Engine - Monorail](https://bugs.chromium.org/p/v8/issues/detail?id=5848) Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/prefer-exponentiation-operator.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/prefer-exponentiation-operator.js) eslint max-nested-callbacks max-nested-callbacks ==================== Enforce a maximum depth that callbacks can be nested Many JavaScript libraries use the callback pattern to manage asynchronous operations. A program of any complexity will most likely need to manage several asynchronous operations at various levels of concurrency. A common pitfall that is easy to fall into is nesting callbacks, which makes code more difficult to read the deeper the callbacks are nested. ``` foo(function () { bar(function () { baz(function() { qux(function () { }); }); }); }); ``` Rule Details ------------ This rule enforces a maximum depth that callbacks can be nested to increase code clarity. Options ------- This rule has a number or object option: * `"max"` (default `10`) enforces a maximum depth that callbacks can be nested **Deprecated:** The object property `maximum` is deprecated; please use the object property `max` instead. ### max Examples of **incorrect** code for this rule with the `{ "max": 3 }` option: ``` /\*eslint max-nested-callbacks: ["error", 3]\*/ foo1(function() { foo2(function() { foo3(function() { foo4(function() { // Do something }); }); }); }); ``` Examples of **correct** code for this rule with the `{ "max": 3 }` option: ``` /\*eslint max-nested-callbacks: ["error", 3]\*/ foo1(handleFoo1); function handleFoo1() { foo2(handleFoo2); } function handleFoo2() { foo3(handleFoo3); } function handleFoo3() { foo4(handleFoo4); } function handleFoo4() { foo5(); } ``` Related Rules ------------- * <complexity> * <max-depth> * <max-len> * <max-lines> * <max-lines-per-function> * <max-params> * <max-statements> Version ------- This rule was introduced in ESLint v0.2.0. Further Reading --------------- [7. Control flow - Mixu’s Node book](http://book.mixu.net/node/ch7.html) [Control Flow in Node - How To Node - NodeJS](https://web.archive.org/web/20220104141150/https://howtonode.org/control-flow) [Control Flow in Node Part II - How To Node - NodeJS](https://web.archive.org/web/20220127215850/https://howtonode.org/control-flow-part-ii) Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/max-nested-callbacks.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/max-nested-callbacks.js)
programming_docs
eslint no-unused-expressions no-unused-expressions ===================== Disallow unused expressions An unused expression which has no effect on the state of the program indicates a logic error. For example, `n + 1;` is not a syntax error, but it might be a typing mistake where a programmer meant an assignment statement `n += 1;` instead. Sometimes, such unused expressions may be eliminated by some build tools in production environment, which possibly breaks application logic. Rule Details ------------ This rule aims to eliminate unused expressions which have no effect on the state of the program. This rule does not apply to function calls or constructor calls with the `new` operator, because they could have *side effects* on the state of the program. ``` var i = 0; function increment() { i += 1; } increment(); // return value is unused, but i changed as a side effect var nThings = 0; function Thing() { nThings += 1; } new Thing(); // constructed object is unused, but nThings changed as a side effect ``` This rule does not apply to directives (which are in the form of literal string expressions such as `"use strict";` at the beginning of a script, module, or function). Sequence expressions (those using a comma, such as `a = 1, b = 2`) are always considered unused unless their return value is assigned or used in a condition evaluation, or a function call is made with the sequence expression value. Options ------- This rule, in its default state, does not require any arguments. If you would like to enable one or more of the following you may pass an object with the options set as follows: * `allowShortCircuit` set to `true` will allow you to use short circuit evaluations in your expressions (Default: `false`). * `allowTernary` set to `true` will enable you to use ternary operators in your expressions similarly to short circuit evaluations (Default: `false`). * `allowTaggedTemplates` set to `true` will enable you to use tagged template literals in your expressions (Default: `false`). * `enforceForJSX` set to `true` will flag unused JSX element expressions (Default: `false`). These options allow unused expressions *only if all* of the code paths either directly change the state (for example, assignment statement) or could have *side effects* (for example, function call). Examples of **incorrect** code for the default `{ "allowShortCircuit": false, "allowTernary": false }` options: ``` /\*eslint no-unused-expressions: "error"\*/ 0 if(0) 0 {0} f(0), {} a && b() a, b() c = a, b; a() && function namedFunctionInExpressionContext () {f();} (function anIncompleteIIFE () {}); injectGlobal`body{ color: red; }` ``` Examples of **correct** code for the default `{ "allowShortCircuit": false, "allowTernary": false }` options: ``` /\*eslint no-unused-expressions: "error"\*/ {} // In this context, this is a block statement, not an object literal {myLabel: someVar} // In this context, this is a block statement with a label and expression, not an object literal function namedFunctionDeclaration () {} (function aGenuineIIFE () {}()); f() a = 0 new C delete a.b void a ``` Note that one or more string expression statements (with or without semi-colons) will only be considered as unused if they are not in the beginning of a script, module, or function (alone and uninterrupted by other statements). Otherwise, they will be treated as part of a “directive prologue”, a section potentially usable by JavaScript engines. This includes “strict mode” directives. Examples of **correct** code for this rule in regard to directives: ``` /\*eslint no-unused-expressions: "error"\*/ "use strict"; "use asm" "use stricter"; "use babel" "any other strings like this in the directive prologue"; "this is still the directive prologue"; function foo() { "bar"; } class Foo { someMethod() { "use strict"; } } ``` Examples of **incorrect** code for this rule in regard to directives: ``` /\*eslint no-unused-expressions: "error"\*/ doSomething(); "use strict"; // this isn't in a directive prologue, because there is a non-directive statement before it function foo() { "bar" + 1; } class Foo { static { "use strict"; // class static blocks do not have directive prologues } } ``` ### allowShortCircuit Examples of **incorrect** code for the `{ "allowShortCircuit": true }` option: ``` /\*eslint no-unused-expressions: ["error", { "allowShortCircuit": true }]\*/ a || b ``` Examples of **correct** code for the `{ "allowShortCircuit": true }` option: ``` /\*eslint no-unused-expressions: ["error", { "allowShortCircuit": true }]\*/ a && b() a() || (b = c) ``` ### allowTernary Examples of **incorrect** code for the `{ "allowTernary": true }` option: ``` /\*eslint no-unused-expressions: ["error", { "allowTernary": true }]\*/ a ? b : 0 a ? b : c() ``` Examples of **correct** code for the `{ "allowTernary": true }` option: ``` /\*eslint no-unused-expressions: ["error", { "allowTernary": true }]\*/ a ? b() : c() a ? (b = c) : d() ``` ### allowShortCircuit and allowTernary Examples of **correct** code for the `{ "allowShortCircuit": true, "allowTernary": true }` options: ``` /\*eslint no-unused-expressions: ["error", { "allowShortCircuit": true, "allowTernary": true }]\*/ a ? b() || (c = d) : e() ``` ### allowTaggedTemplates Examples of **incorrect** code for the `{ "allowTaggedTemplates": true }` option: ``` /\*eslint no-unused-expressions: ["error", { "allowTaggedTemplates": true }]\*/ `some untagged template string`; ``` Examples of **correct** code for the `{ "allowTaggedTemplates": true }` option: ``` /\*eslint no-unused-expressions: ["error", { "allowTaggedTemplates": true }]\*/ tag`some tagged template string`; ``` ### enforceForJSX JSX is most-commonly used in the React ecosystem, where it is compiled to `React.createElement` expressions. Though free from side-effects, these calls are not automatically flagged by the `no-unused-expression` rule. If you’re using React, or any other side-effect-free JSX pragma, this option can be enabled to flag these expressions. Examples of **incorrect** code for the `{ "enforceForJSX": true }` option: ``` /\*eslint no-unused-expressions: ["error", { "enforceForJSX": true }]\*/ <MyComponent />; <></>; ``` Examples of **correct** code for the `{ "enforceForJSX": true }` option: ``` /\*eslint no-unused-expressions: ["error", { "enforceForJSX": true }]\*/ var myComponentPartial = <MyComponent />; var myFragment = <></>; ``` Version ------- This rule was introduced in ESLint v0.1.0. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/no-unused-expressions.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/no-unused-expressions.js) eslint keyword-spacing keyword-spacing =============== Enforce consistent spacing before and after keywords 🔧 Fixable Some problems reported by this rule are automatically fixable by the `--fix` [command line](keyword-spacing../user-guide/command-line-interface#--fix) option Keywords are syntax elements of JavaScript, such as `try` and `if`. These keywords have special meaning to the language and so often appear in a different color in code editors. As an important part of the language, style guides often refer to the spacing that should be used around keywords. For example, you might have a style guide that says keywords should be always surrounded by spaces, which would mean `if-else` statements must look like this: ``` if (foo) { // ... } else { // ... } ``` Of course, you could also have a style guide that disallows spaces around keywords. However, if you want to enforce the style of spacing between the `function` keyword and the following opening parenthesis, please refer to [space-before-function-paren](keyword-spacingspace-before-function-paren). Rule Details ------------ This rule enforces consistent spacing around keywords and keyword-like tokens: `as` (in module declarations), `async` (of async functions), `await` (of await expressions), `break`, `case`, `catch`, `class`, `const`, `continue`, `debugger`, `default`, `delete`, `do`, `else`, `export`, `extends`, `finally`, `for`, `from` (in module declarations), `function`, `get` (of getters), `if`, `import`, `in` (in for-in statements), `let`, `new`, `of` (in for-of statements), `return`, `set` (of setters), `static`, `super`, `switch`, `this`, `throw`, `try`, `typeof`, `var`, `void`, `while`, `with`, and `yield`. This rule is designed carefully not to conflict with other spacing rules: it does not apply to spacing where other rules report problems. Options ------- This rule has an object option: * `"before": true` (default) requires at least one space before keywords * `"before": false` disallows spaces before keywords * `"after": true` (default) requires at least one space after keywords * `"after": false` disallows spaces after keywords * `"overrides"` allows overriding spacing style for specified keywords ### before Examples of **incorrect** code for this rule with the default `{ "before": true }` option: ``` /\*eslint keyword-spacing: ["error", { "before": true }]\*/ if (foo) { //... }else if (bar) { //... }else { //... } ``` Examples of **correct** code for this rule with the default `{ "before": true }` option: ``` /\*eslint keyword-spacing: ["error", { "before": true }]\*/ /\*eslint-env es6\*/ if (foo) { //... } else if (bar) { //... } else { //... } // Avoid conflict with `array-bracket-spacing` let a = [this]; let b = [function() {}]; // Avoid conflict with `arrow-spacing` let a = ()=> this.foo; // Avoid conflict with `block-spacing` {function foo() {}} // Avoid conflict with `comma-spacing` let a = [100,this.foo, this.bar]; // Avoid conflict with `computed-property-spacing` obj[this.foo] = 0; // Avoid conflict with `generator-star-spacing` function \*foo() {} // Avoid conflict with `key-spacing` let obj = { foo:function() {} }; // Avoid conflict with `object-curly-spacing` let obj = {foo: this}; // Avoid conflict with `semi-spacing` let a = this;function foo() {} // Avoid conflict with `space-in-parens` (function () {})(); // Avoid conflict with `space-infix-ops` if ("foo"in {foo: 0}) {} if (10+this.foo<= this.bar) {} // Avoid conflict with `jsx-curly-spacing` let a = <A foo={this.foo} bar={function(){}} /> ``` Examples of **incorrect** code for this rule with the `{ "before": false }` option: ``` /\*eslint keyword-spacing: ["error", { "before": false }]\*/ if (foo) { //... } else if (bar) { //... } else { //... } ``` Examples of **correct** code for this rule with the `{ "before": false }` option: ``` /\*eslint keyword-spacing: ["error", { "before": false }]\*/ if (foo) { //... }else if (bar) { //... }else { //... } ``` ### after Examples of **incorrect** code for this rule with the default `{ "after": true }` option: ``` /\*eslint keyword-spacing: ["error", { "after": true }]\*/ if(foo) { //... } else if(bar) { //... } else{ //... } ``` Examples of **correct** code for this rule with the default `{ "after": true }` option: ``` /\*eslint keyword-spacing: ["error", { "after": true }]\*/ if (foo) { //... } else if (bar) { //... } else { //... } // Avoid conflict with `array-bracket-spacing` let a = [this]; // Avoid conflict with `arrow-spacing` let a = ()=> this.foo; // Avoid conflict with `comma-spacing` let a = [100, this.foo, this.bar]; // Avoid conflict with `computed-property-spacing` obj[this.foo] = 0; // Avoid conflict with `generator-star-spacing` function\* foo() {} // Avoid conflict with `key-spacing` let obj = { foo:function() {} }; // Avoid conflict with `func-call-spacing` class A { constructor() { super(); } } // Avoid conflict with `object-curly-spacing` let obj = {foo: this}; // Avoid conflict with `semi-spacing` let a = this;function foo() {} // Avoid conflict with `space-before-function-paren` function() {} // Avoid conflict with `space-infix-ops` if ("foo"in{foo: 0}) {} if (10+this.foo<= this.bar) {} // Avoid conflict with `space-unary-ops` function\* foo(a) { return yield+a; } // Avoid conflict with `yield-star-spacing` function\* foo(a) { return yield\* a; } // Avoid conflict with `jsx-curly-spacing` let a = <A foo={this.foo} bar={function(){}} /> ``` Examples of **incorrect** code for this rule with the `{ "after": false }` option: ``` /\*eslint keyword-spacing: ["error", { "after": false }]\*/ if (foo) { //... } else if (bar) { //... } else { //... } ``` Examples of **correct** code for this rule with the `{ "after": false }` option: ``` /\*eslint keyword-spacing: ["error", { "after": false }]\*/ if(foo) { //... } else if(bar) { //... } else{ //... } ``` ### overrides Examples of **correct** code for this rule with the `{ "overrides": { "if": { "after": false }, "for": { "after": false }, "while": { "after": false }, "static": { "after": false }, "as": { "after": false } } }` option: ``` /\*eslint keyword-spacing: ["error", { "overrides": { "if": { "after": false }, "for": { "after": false }, "while": { "after": false }, "static": { "after": false }, "as": { "after": false } } }]\*/ if(foo) { //... } else if(bar) { //... } else { //... } for(;;); while(true) { //... } class C { static{ //... } } export { C as"my class" }; ``` When Not To Use It ------------------ If you don’t want to enforce consistency on keyword spacing, then it’s safe to disable this rule. Version ------- This rule was introduced in ESLint v2.0.0-beta.1. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/keyword-spacing.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/keyword-spacing.js) eslint max-statements max-statements ============== Enforce a maximum number of statements allowed in function blocks The `max-statements` rule allows you to specify the maximum number of statements allowed in a function. ``` function foo() { var bar = 1; // one statement var baz = 2; // two statements var qux = 3; // three statements } ``` Rule Details ------------ This rule enforces a maximum number of statements allowed in function blocks. Options ------- This rule has a number or object option: * `"max"` (default `10`) enforces a maximum number of statements allows in function blocks **Deprecated:** The object property `maximum` is deprecated; please use the object property `max` instead. This rule has an object option: * `"ignoreTopLevelFunctions": true` ignores top-level functions ### max Examples of **incorrect** code for this rule with the default `{ "max": 10 }` option: ``` /\*eslint max-statements: ["error", 10]\*/ /\*eslint-env es6\*/ function foo() { var foo1 = 1; var foo2 = 2; var foo3 = 3; var foo4 = 4; var foo5 = 5; var foo6 = 6; var foo7 = 7; var foo8 = 8; var foo9 = 9; var foo10 = 10; var foo11 = 11; // Too many. } let foo = () => { var foo1 = 1; var foo2 = 2; var foo3 = 3; var foo4 = 4; var foo5 = 5; var foo6 = 6; var foo7 = 7; var foo8 = 8; var foo9 = 9; var foo10 = 10; var foo11 = 11; // Too many. }; ``` Examples of **correct** code for this rule with the default `{ "max": 10 }` option: ``` /\*eslint max-statements: ["error", 10]\*/ /\*eslint-env es6\*/ function foo() { var foo1 = 1; var foo2 = 2; var foo3 = 3; var foo4 = 4; var foo5 = 5; var foo6 = 6; var foo7 = 7; var foo8 = 8; var foo9 = 9; var foo10 = 10; return function () { // The number of statements in the inner function does not count toward the // statement maximum. return 42; }; } let foo = () => { var foo1 = 1; var foo2 = 2; var foo3 = 3; var foo4 = 4; var foo5 = 5; var foo6 = 6; var foo7 = 7; var foo8 = 8; var foo9 = 9; var foo10 = 10; return function () { // The number of statements in the inner function does not count toward the // statement maximum. return 42; }; } ``` Note that this rule does not apply to class static blocks, and that statements in class static blocks do not count as statements in the enclosing function. Examples of **correct** code for this rule with `{ "max": 2 }` option: ``` /\*eslint max-statements: ["error", 2]\*/ function foo() { let one; let two = class { static { let three; let four; let five; if (six) { let seven; let eight; let nine; } } }; } ``` ### ignoreTopLevelFunctions Examples of additional **correct** code for this rule with the `{ "max": 10 }, { "ignoreTopLevelFunctions": true }` options: ``` /\*eslint max-statements: ["error", 10, { "ignoreTopLevelFunctions": true }]\*/ function foo() { var foo1 = 1; var foo2 = 2; var foo3 = 3; var foo4 = 4; var foo5 = 5; var foo6 = 6; var foo7 = 7; var foo8 = 8; var foo9 = 9; var foo10 = 10; var foo11 = 11; } ``` Related Rules ------------- * <complexity> * <max-depth> * <max-len> * <max-lines> * <max-lines-per-function> * <max-nested-callbacks> * <max-params> Version ------- This rule was introduced in ESLint v0.0.9. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/max-statements.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/max-statements.js) eslint no-fallthrough no-fallthrough ============== Disallow fallthrough of `case` statements ✅ Recommended The `"extends": "eslint:recommended"` property in a [configuration file](no-fallthrough../user-guide/configuring/configuration-files#extending-configuration-files) enables this rule The `switch` statement in JavaScript is one of the more error-prone constructs of the language thanks in part to the ability to “fall through” from one `case` to the next. For example: ``` switch(foo) { case 1: doSomething(); case 2: doSomethingElse(); } ``` In this example, if `foo` is `1`, then execution will flow through both cases, as the first falls through to the second. You can prevent this by using `break`, as in this example: ``` switch(foo) { case 1: doSomething(); break; case 2: doSomethingElse(); } ``` That works fine when you don’t want a fallthrough, but what if the fallthrough is intentional, there is no way to indicate that in the language. It’s considered a best practice to always indicate when a fallthrough is intentional using a comment which matches the `/falls?\s?through/i` regular expression: ``` switch(foo) { case 1: doSomething(); // falls through case 2: doSomethingElse(); } switch(foo) { case 1: doSomething(); // fall through case 2: doSomethingElse(); } switch(foo) { case 1: doSomething(); // fallsthrough case 2: doSomethingElse(); } switch(foo) { case 1: { doSomething(); // falls through } case 2: { doSomethingElse(); } } ``` In this example, there is no confusion as to the expected behavior. It is clear that the first case is meant to fall through to the second case. Rule Details ------------ This rule is aimed at eliminating unintentional fallthrough of one case to the other. As such, it flags any fallthrough scenarios that are not marked by a comment. Examples of **incorrect** code for this rule: ``` /\*eslint no-fallthrough: "error"\*/ switch(foo) { case 1: doSomething(); case 2: doSomething(); } ``` Examples of **correct** code for this rule: ``` /\*eslint no-fallthrough: "error"\*/ switch(foo) { case 1: doSomething(); break; case 2: doSomething(); } function bar(foo) { switch(foo) { case 1: doSomething(); return; case 2: doSomething(); } } switch(foo) { case 1: doSomething(); throw new Error("Boo!"); case 2: doSomething(); } switch(foo) { case 1: case 2: doSomething(); } switch(foo) { case 1: doSomething(); // falls through case 2: doSomething(); } switch(foo) { case 1: { doSomething(); // falls through } case 2: { doSomethingElse(); } } ``` Note that the last `case` statement in these examples does not cause a warning because there is nothing to fall through into. Options ------- This rule has an object option: * Set the `commentPattern` option to a regular expression string to change the test for intentional fallthrough comment. * Set the `allowEmptyCase` option to `true` to allow empty cases regardless of the layout. By default, this rule does not require a fallthrough comment after an empty `case` only if the empty `case` and the next `case` are on the same line or on consecutive lines. ### commentPattern Examples of **correct** code for the `{ "commentPattern": "break[\\s\\w]*omitted" }` option: ``` /\*eslint no-fallthrough: ["error", { "commentPattern": "break[\\s\\w]\*omitted" }]\*/ switch(foo) { case 1: doSomething(); // break omitted case 2: doSomething(); } switch(foo) { case 1: doSomething(); // caution: break is omitted intentionally default: doSomething(); } ``` ### allowEmptyCase Examples of **correct** code for the `{ "allowEmptyCase": true }` option: ``` /\* eslint no-fallthrough: ["error", { "allowEmptyCase": true }] \*/ switch(foo){ case 1: case 2: doSomething(); } switch(foo){ case 1: /\* Put a message here \*/ case 2: doSomething(); } ``` When Not To Use It ------------------ If you don’t want to enforce that each `case` statement should end with a `throw`, `return`, `break`, or comment, then you can safely turn this rule off. Related Rules ------------- * <default-case> Version ------- This rule was introduced in ESLint v0.0.7. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/no-fallthrough.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/no-fallthrough.js)
programming_docs
eslint complexity complexity ========== Enforce a maximum cyclomatic complexity allowed in a program Cyclomatic complexity measures the number of linearly independent paths through a program’s source code. This rule allows setting a cyclomatic complexity threshold. ``` function a(x) { if (true) { return x; // 1st path } else if (false) { return x+1; // 2nd path } else { return 4; // 3rd path } } ``` Rule Details ------------ This rule is aimed at reducing code complexity by capping the amount of cyclomatic complexity allowed in a program. As such, it will warn when the cyclomatic complexity crosses the configured threshold (default is `20`). Examples of **incorrect** code for a maximum of 2: ``` /\*eslint complexity: ["error", 2]\*/ function a(x) { if (true) { return x; } else if (false) { return x+1; } else { return 4; // 3rd path } } function b() { foo ||= 1; bar &&= 1; } ``` Examples of **correct** code for a maximum of 2: ``` /\*eslint complexity: ["error", 2]\*/ function a(x) { if (true) { return x; } else { return 4; } } function b() { foo ||= 1; } ``` Class field initializers and class static blocks are implicit functions. Therefore, their complexity is calculated separately for each initializer and each static block, and it doesn’t contribute to the complexity of the enclosing code. Examples of additional **incorrect** code for a maximum of 2: ``` /\*eslint complexity: ["error", 2]\*/ class C { x = a || b || c; // this initializer has complexity = 3 } class D { // this static block has complexity = 3 static { if (foo) { bar = baz || qux; } } } ``` Examples of additional **correct** code for a maximum of 2: ``` /\*eslint complexity: ["error", 2]\*/ function foo() { // this function has complexity = 1 class C { x = a + b; // this initializer has complexity = 1 y = c || d; // this initializer has complexity = 2 z = e && f; // this initializer has complexity = 2 static p = g || h; // this initializer has complexity = 2 static q = i ? j : k; // this initializer has complexity = 2 static { // this static block has complexity = 2 if (foo) { baz = bar; } } static { // this static block has complexity = 2 qux = baz || quux; } } } ``` Options ------- Optionally, you may specify a `max` object property: ``` "complexity": ["error", 2] ``` is equivalent to ``` "complexity": ["error", { "max": 2 }] ``` **Deprecated:** the object property `maximum` is deprecated. Please use the property `max` instead. When Not To Use It ------------------ If you can’t determine an appropriate complexity limit for your code, then it’s best to disable this rule. Related Rules ------------- * <max-depth> * <max-len> * <max-lines> * <max-lines-per-function> * <max-nested-callbacks> * <max-params> * <max-statements> Version ------- This rule was introduced in ESLint v0.0.9. Further Reading --------------- [Cyclomatic complexity - Wikipedia](https://en.wikipedia.org/wiki/Cyclomatic_complexity) [Complexity Analysis of JavaScript Code](https://ariya.io/2012/12/complexity-analysis-of-javascript-code) [Complexity for JavaScript](https://craftsmanshipforsoftware.com/2015/05/25/complexity-for-javascript/) [About complexity | JSComplexity.org](https://web.archive.org/web/20160808115119/http://jscomplexity.org/complexity) [Complexity has no default · Issue #4808 · eslint/eslint](https://github.com/eslint/eslint/issues/4808#issuecomment-167795140) Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/complexity.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/complexity.js) eslint no-array-constructor no-array-constructor ==================== Disallow `Array` constructors Use of the `Array` constructor to construct a new array is generally discouraged in favor of array literal notation because of the single-argument pitfall and because the `Array` global may be redefined. The exception is when the Array constructor is used to intentionally create sparse arrays of a specified size by giving the constructor a single numeric argument. Rule Details ------------ This rule disallows `Array` constructors. Examples of **incorrect** code for this rule: ``` /\*eslint no-array-constructor: "error"\*/ Array(0, 1, 2) new Array(0, 1, 2) ``` Examples of **correct** code for this rule: ``` /\*eslint no-array-constructor: "error"\*/ Array(500) new Array(someOtherArray.length) [0, 1, 2] ``` When Not To Use It ------------------ This rule enforces a nearly universal stylistic concern. That being said, this rule may be disabled if the constructor style is preferred. Related Rules ------------- * <no-new-object> * <no-new-wrappers> Version ------- This rule was introduced in ESLint v0.4.0. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/no-array-constructor.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/no-array-constructor.js) eslint no-lonely-if no-lonely-if ============ Disallow `if` statements as the only statement in `else` blocks 🔧 Fixable Some problems reported by this rule are automatically fixable by the `--fix` [command line](no-lonely-if../user-guide/command-line-interface#--fix) option If an `if` statement is the only statement in the `else` block, it is often clearer to use an `else if` form. ``` if (foo) { // ... } else { if (bar) { // ... } } ``` should be rewritten as ``` if (foo) { // ... } else if (bar) { // ... } ``` Rule Details ------------ This rule disallows `if` statements as the only statement in `else` blocks. Examples of **incorrect** code for this rule: ``` /\*eslint no-lonely-if: "error"\*/ if (condition) { // ... } else { if (anotherCondition) { // ... } } if (condition) { // ... } else { if (anotherCondition) { // ... } else { // ... } } ``` Examples of **correct** code for this rule: ``` /\*eslint no-lonely-if: "error"\*/ if (condition) { // ... } else if (anotherCondition) { // ... } if (condition) { // ... } else if (anotherCondition) { // ... } else { // ... } if (condition) { // ... } else { if (anotherCondition) { // ... } doSomething(); } ``` When Not To Use It ------------------ Disable this rule if the code is clearer without requiring the `else if` form. Version ------- This rule was introduced in ESLint v0.6.0. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/no-lonely-if.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/no-lonely-if.js) eslint one-var-declaration-per-line one-var-declaration-per-line ============================ Require or disallow newlines around variable declarations 🔧 Fixable Some problems reported by this rule are automatically fixable by the `--fix` [command line](one-var-declaration-per-line../user-guide/command-line-interface#--fix) option Some developers declare multiple var statements on the same line: ``` var foo, bar, baz; ``` Others prefer to declare one var per line. ``` var foo, bar, baz; ``` Keeping to one of these styles across a project’s codebase can help with maintaining code consistency. Rule Details ------------ This rule enforces a consistent newlines around variable declarations. This rule ignores variable declarations inside `for` loop conditionals. Options ------- This rule has a single string option: * `"initializations"` (default) enforces a newline around variable initializations * `"always"` enforces a newline around variable declarations ### initializations Examples of **incorrect** code for this rule with the default `"initializations"` option: ``` /\*eslint one-var-declaration-per-line: ["error", "initializations"]\*/ /\*eslint-env es6\*/ var a, b, c = 0; let a, b = 0, c; ``` Examples of **correct** code for this rule with the default `"initializations"` option: ``` /\*eslint one-var-declaration-per-line: ["error", "initializations"]\*/ /\*eslint-env es6\*/ var a, b; let a, b; let a, b = 0; ``` ### always Examples of **incorrect** code for this rule with the `"always"` option: ``` /\*eslint one-var-declaration-per-line: ["error", "always"]\*/ /\*eslint-env es6\*/ var a, b; let a, b = 0; const a = 0, b = 0; ``` Examples of **correct** code for this rule with the `"always"` option: ``` /\*eslint one-var-declaration-per-line: ["error", "always"]\*/ /\*eslint-env es6\*/ var a, b; let a, b = 0; ``` Related Rules ------------- * <one-var> Version ------- This rule was introduced in ESLint v2.0.0-beta.3. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/one-var-declaration-per-line.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/one-var-declaration-per-line.js) eslint linebreak-style linebreak-style =============== Enforce consistent linebreak style 🔧 Fixable Some problems reported by this rule are automatically fixable by the `--fix` [command line](linebreak-style../user-guide/command-line-interface#--fix) option When developing with a lot of people all having different editors, VCS applications and operating systems it may occur that different line endings are written by either of the mentioned (might especially happen when using the windows and mac versions of SourceTree together). The linebreaks (new lines) used in windows operating system are usually *carriage returns* (CR) followed by a *line feed* (LF) making it a *carriage return line feed* (CRLF) whereas Linux and Unix use a simple *line feed* (LF). The corresponding *control sequences* are `"\n"` (for LF) and `"\r\n"` for (CRLF). Many versioning systems (like git and subversion) can automatically ensure the correct ending. However to cover all contingencies, you can activate this rule. Rule Details ------------ This rule enforces consistent line endings independent of operating system, VCS, or editor used across your codebase. ### Options This rule has a string option: * `"unix"` (default) enforces the usage of Unix line endings: `\n` for LF. * `"windows"` enforces the usage of Windows line endings: `\r\n` for CRLF. ### unix Examples of **incorrect** code for this rule with the default `"unix"` option: ``` /\*eslint linebreak-style: ["error", "unix"]\*/ var a = 'a'; // \r\n ``` Examples of **correct** code for this rule with the default `"unix"` option: ``` /\*eslint linebreak-style: ["error", "unix"]\*/ var a = 'a', // \n b = 'b'; // \n // \n function foo(params) { // \n // do stuff \n }// \n ``` ### windows Examples of **incorrect** code for this rule with the `"windows"` option: ``` /\*eslint linebreak-style: ["error", "windows"]\*/ var a = 'a'; // \n ``` Examples of **correct** code for this rule with the `"windows"` option: ``` /\*eslint linebreak-style: ["error", "windows"]\*/ var a = 'a', // \r\n b = 'b'; // \r\n // \r\n function foo(params) { // \r\n // do stuff \r\n } // \r\n ``` ### Using this rule with version control systems Version control systems sometimes have special behavior for linebreaks. To make it easy for developers to contribute to your codebase from different platforms, you may want to configure your VCS to handle linebreaks appropriately. For example, the default behavior of [git](https://git-scm.com/) on Windows systems is to convert LF linebreaks to CRLF when checking out files, but to store the linebreaks as LF when committing a change. This will cause the `linebreak-style` rule to report errors if configured with the `"unix"` setting, because the files that ESLint sees will have CRLF linebreaks. If you use git, you may want to add a line to your [`.gitattributes` file](https://git-scm.com/docs/gitattributes) to prevent git from converting linebreaks in `.js` files: ``` *.js text eol=lf ``` When Not To Use It ------------------ If you aren’t concerned about having different line endings within your code, then you can safely turn this rule off. Compatibility ------------- * **JSCS**: [validateLineBreaks](https://jscs-dev.github.io/rule/validateLineBreaks) Version ------- This rule was introduced in ESLint v0.21.0. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/linebreak-style.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/linebreak-style.js) eslint no-new no-new ====== Disallow `new` operators outside of assignments or comparisons The goal of using `new` with a constructor is typically to create an object of a particular type and store that object in a variable, such as: ``` var person = new Person(); ``` It’s less common to use `new` and not store the result, such as: ``` new Person(); ``` In this case, the created object is thrown away because its reference isn’t stored anywhere, and in many cases, this means that the constructor should be replaced with a function that doesn’t require `new` to be used. Rule Details ------------ This rule is aimed at maintaining consistency and convention by disallowing constructor calls using the `new` keyword that do not assign the resulting object to a variable. Examples of **incorrect** code for this rule: ``` /\*eslint no-new: "error"\*/ new Thing(); ``` Examples of **correct** code for this rule: ``` /\*eslint no-new: "error"\*/ var thing = new Thing(); Thing(); ``` Version ------- This rule was introduced in ESLint v0.0.7. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/no-new.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/no-new.js) eslint no-new-native-nonconstructor no-new-native-nonconstructor ============================ Disallow `new` operators with global non-constructor functions It is a convention in JavaScript that global variables beginning with an uppercase letter typically represent classes that can be instantiated using the `new` operator, such as `new Array` and `new Map`. Confusingly, JavaScript also provides some global variables that begin with an uppercase letter that cannot be called using the `new` operator and will throw an error if you attempt to do so. These are typically functions that are related to data types and are easy to mistake for classes. Consider the following example: ``` // throws a TypeError let foo = new Symbol("foo"); // throws a TypeError let result = new BigInt(9007199254740991); ``` Both `new Symbol` and `new BigInt` throw a type error because they are functions and not classes. It is easy to make this mistake by assuming the uppercase letters indicate classes. Rule Details ------------ This rule is aimed at preventing the accidental calling of native JavaScript global functions with the `new` operator. These functions are: * `Symbol` * `BigInt` Examples -------- Examples of **incorrect** code for this rule: ``` /\*eslint no-new-native-nonconstructor: "error"\*/ /\*eslint-env es2022\*/ var foo = new Symbol('foo'); var bar = new BigInt(9007199254740991); ``` Examples of **correct** code for this rule: ``` /\*eslint no-new-native-nonconstructor: "error"\*/ /\*eslint-env es2022\*/ var foo = Symbol('foo'); var bar = BigInt(9007199254740991); // Ignores shadowed Symbol. function baz(Symbol) { const qux = new Symbol("baz"); } function quux(BigInt) { const corge = new BigInt(9007199254740991); } ``` When Not To Use It ------------------ This rule should not be used in ES3/5 environments. Related Rules ------------- * <no-obj-calls> Version ------- This rule was introduced in ESLint v8.27.0. Further Reading --------------- [ECMAScript® 2023 Language Specification](https://tc39.es/ecma262/#sec-symbol-constructor) [ECMAScript® 2023 Language Specification](https://tc39.es/ecma262/#sec-bigint-constructor) Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/no-new-native-nonconstructor.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/no-new-native-nonconstructor.js) eslint no-case-declarations no-case-declarations ==================== Disallow lexical declarations in case clauses ✅ Recommended The `"extends": "eslint:recommended"` property in a [configuration file](no-case-declarations../user-guide/configuring/configuration-files#extending-configuration-files) enables this rule This rule disallows lexical declarations (`let`, `const`, `function` and `class`) in `case`/`default` clauses. The reason is that the lexical declaration is visible in the entire switch block but it only gets initialized when it is assigned, which will only happen if the case where it is defined is reached. To ensure that the lexical declaration only applies to the current case clause wrap your clauses in blocks. Rule Details ------------ This rule aims to prevent access to uninitialized lexical bindings as well as accessing hoisted functions across case clauses. Examples of **incorrect** code for this rule: ``` /\*eslint no-case-declarations: "error"\*/ /\*eslint-env es6\*/ switch (foo) { case 1: let x = 1; break; case 2: const y = 2; break; case 3: function f() {} break; default: class C {} } ``` Examples of **correct** code for this rule: ``` /\*eslint no-case-declarations: "error"\*/ /\*eslint-env es6\*/ // Declarations outside switch-statements are valid const a = 0; switch (foo) { // The following case clauses are wrapped into blocks using brackets case 1: { let x = 1; break; } case 2: { const y = 2; break; } case 3: { function f() {} break; } case 4: // Declarations using var without brackets are valid due to function-scope hoisting var z = 4; break; default: { class C {} } } ``` When Not To Use It ------------------ If you depend on fall through behavior and want access to bindings introduced in the case block. Related Rules ------------- * <no-fallthrough> Version ------- This rule was introduced in ESLint v1.9.0. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/no-case-declarations.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/no-case-declarations.js) eslint prefer-rest-params prefer-rest-params ================== Require rest parameters instead of `arguments` There are rest parameters in ES2015. We can use that feature for variadic functions instead of the `arguments` variable. `arguments` does not have methods of `Array.prototype`, so it’s a bit of an inconvenience. Rule Details ------------ This rule is aimed to flag usage of `arguments` variables. Examples -------- Examples of **incorrect** code for this rule: ``` /\*eslint prefer-rest-params: "error"\*/ function foo() { console.log(arguments); } function foo(action) { var args = Array.prototype.slice.call(arguments, 1); action.apply(null, args); } function foo(action) { var args = [].slice.call(arguments, 1); action.apply(null, args); } ``` Examples of **correct** code for this rule: ``` /\*eslint prefer-rest-params: "error"\*/ function foo(...args) { console.log(args); } function foo(action, ...args) { action.apply(null, args); // or `action(...args)`, related to the `prefer-spread` rule. } // Note: the implicit arguments can be overwritten. function foo(arguments) { console.log(arguments); // This is the first argument. } function foo() { var arguments = 0; console.log(arguments); // This is a local variable. } ``` When Not To Use It ------------------ This rule should not be used in ES3/5 environments. In ES2015 (ES6) or later, if you don’t want to be notified about `arguments` variables, then it’s safe to disable this rule. Related Rules ------------- * <prefer-spread> Version ------- This rule was introduced in ESLint v2.0.0-alpha-1. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/prefer-rest-params.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/prefer-rest-params.js)
programming_docs
eslint no-prototype-builtins no-prototype-builtins ===================== Disallow calling some `Object.prototype` methods directly on objects ✅ Recommended The `"extends": "eslint:recommended"` property in a [configuration file](no-prototype-builtins../user-guide/configuring/configuration-files#extending-configuration-files) enables this rule In ECMAScript 5.1, `Object.create` was added, which enables the creation of objects with a specified `[[Prototype]]`. `Object.create(null)` is a common pattern used to create objects that will be used as a Map. This can lead to errors when it is assumed that objects will have properties from `Object.prototype`. This rule prevents calling some `Object.prototype` methods directly from an object. Additionally, objects can have properties that shadow the builtins on `Object.prototype`, potentially causing unintended behavior or denial-of-service security vulnerabilities. For example, it would be unsafe for a webserver to parse JSON input from a client and call `hasOwnProperty` directly on the resulting object, because a malicious client could send a JSON value like `{"hasOwnProperty": 1}` and cause the server to crash. To avoid subtle bugs like this, it’s better to always call these methods from `Object.prototype`. For example, `foo.hasOwnProperty("bar")` should be replaced with `Object.prototype.hasOwnProperty.call(foo, "bar")`. Rule Details ------------ This rule disallows calling some `Object.prototype` methods directly on object instances. Examples of **incorrect** code for this rule: ``` /\*eslint no-prototype-builtins: "error"\*/ var hasBarProperty = foo.hasOwnProperty("bar"); var isPrototypeOfBar = foo.isPrototypeOf(bar); var barIsEnumerable = foo.propertyIsEnumerable("bar"); ``` Examples of **correct** code for this rule: ``` /\*eslint no-prototype-builtins: "error"\*/ var hasBarProperty = Object.prototype.hasOwnProperty.call(foo, "bar"); var isPrototypeOfBar = Object.prototype.isPrototypeOf.call(foo, bar); var barIsEnumerable = {}.propertyIsEnumerable.call(foo, "bar"); ``` When Not To Use It ------------------ You may want to turn this rule off if your code only touches objects with hardcoded keys, and you will never use an object that shadows an `Object.prototype` method or which does not inherit from `Object.prototype`. Version ------- This rule was introduced in ESLint v2.11.0. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/no-prototype-builtins.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/no-prototype-builtins.js) eslint no-return-assign no-return-assign ================ Disallow assignment operators in `return` statements One of the interesting, and sometimes confusing, aspects of JavaScript is that assignment can happen at almost any point. Because of this, an errant equals sign can end up causing assignment when the true intent was to do a comparison. This is especially true when using a `return` statement. For example: ``` function doSomething() { return foo = bar + 2; } ``` It is difficult to tell the intent of the `return` statement here. It’s possible that the function is meant to return the result of `bar + 2`, but then why is it assigning to `foo`? It’s also possible that the intent was to use a comparison operator such as `==` and that this code is an error. Because of this ambiguity, it’s considered a best practice to not use assignment in `return` statements. Rule Details ------------ This rule aims to eliminate assignments from `return` statements. As such, it will warn whenever an assignment is found as part of `return`. Options ------- The rule takes one option, a string, which must contain one of the following values: * `except-parens` (default): Disallow assignments unless they are enclosed in parentheses. * `always`: Disallow all assignments. ### except-parens This is the default option. It disallows assignments unless they are enclosed in parentheses. Examples of **incorrect** code for the default `"except-parens"` option: ``` /\*eslint no-return-assign: "error"\*/ function doSomething() { return foo = bar + 2; } function doSomething() { return foo += 2; } const foo = (a, b) => a = b const bar = (a, b, c) => (a = b, c == b) function doSomething() { return foo = bar && foo > 0; } ``` Examples of **correct** code for the default `"except-parens"` option: ``` /\*eslint no-return-assign: "error"\*/ function doSomething() { return foo == bar + 2; } function doSomething() { return foo === bar + 2; } function doSomething() { return (foo = bar + 2); } const foo = (a, b) => (a = b) const bar = (a, b, c) => ((a = b), c == b) function doSomething() { return (foo = bar) && foo > 0; } ``` ### always This option disallows all assignments in `return` statements. All assignments are treated as problems. Examples of **incorrect** code for the `"always"` option: ``` /\*eslint no-return-assign: ["error", "always"]\*/ function doSomething() { return foo = bar + 2; } function doSomething() { return foo += 2; } function doSomething() { return (foo = bar + 2); } ``` Examples of **correct** code for the `"always"` option: ``` /\*eslint no-return-assign: ["error", "always"]\*/ function doSomething() { return foo == bar + 2; } function doSomething() { return foo === bar + 2; } ``` When Not To Use It ------------------ If you want to allow the use of assignment operators in a `return` statement, then you can safely disable this rule. Version ------- This rule was introduced in ESLint v0.0.9. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/no-return-assign.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/no-return-assign.js) eslint default-param-last default-param-last ================== Enforce default parameters to be last Putting default parameter at last allows function calls to omit optional tail arguments. ``` // Correct: optional argument can be omitted function createUser(id, isAdmin = false) {} createUser("tabby") // Incorrect: optional argument can \*\*not\*\* be omitted function createUser(isAdmin = false, id) {} createUser(undefined, "tabby") ``` Rule Details ------------ This rule enforces default parameters to be the last of parameters. Examples of **incorrect** code for this rule: ``` /\* eslint default-param-last: ["error"] \*/ function f(a = 0, b) {} function f(a, b = 0, c) {} ``` Examples of **correct** code for this rule: ``` /\* eslint default-param-last: ["error"] \*/ function f(a, b = 0) {} ``` Version ------- This rule was introduced in ESLint v6.4.0. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/default-param-last.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/default-param-last.js) eslint no-async-promise-executor no-async-promise-executor ========================= Disallow using an async function as a Promise executor ✅ Recommended The `"extends": "eslint:recommended"` property in a [configuration file](no-async-promise-executor../user-guide/configuring/configuration-files#extending-configuration-files) enables this rule The `new Promise` constructor accepts an *executor* function as an argument, which has `resolve` and `reject` parameters that can be used to control the state of the created Promise. For example: ``` const result = new Promise(function executor(resolve, reject) { readFile('foo.txt', function(err, result) { if (err) { reject(err); } else { resolve(result); } }); }); ``` The executor function can also be an `async function`. However, this is usually a mistake, for a few reasons: * If an async executor function throws an error, the error will be lost and won’t cause the newly-constructed `Promise` to reject. This could make it difficult to debug and handle some errors. * If a Promise executor function is using `await`, this is usually a sign that it is not actually necessary to use the `new Promise` constructor, or the scope of the `new Promise` constructor can be reduced. Rule Details ------------ This rule aims to disallow async Promise executor functions. Examples of **incorrect** code for this rule: ``` const foo = new Promise(async (resolve, reject) => { readFile('foo.txt', function(err, result) { if (err) { reject(err); } else { resolve(result); } }); }); const result = new Promise(async (resolve, reject) => { resolve(await foo); }); ``` Examples of **correct** code for this rule: ``` const foo = new Promise((resolve, reject) => { readFile('foo.txt', function(err, result) { if (err) { reject(err); } else { resolve(result); } }); }); const result = Promise.resolve(foo); ``` When Not To Use It ------------------ If your codebase doesn’t support async function syntax, there’s no need to enable this rule. Version ------- This rule was introduced in ESLint v5.3.0. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/no-async-promise-executor.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/no-async-promise-executor.js) eslint no-eq-null no-eq-null ========== Disallow `null` comparisons without type-checking operators Comparing to `null` without a type-checking operator (`==` or `!=`), can have unintended results as the comparison will evaluate to true when comparing to not just a `null`, but also an `undefined` value. ``` if (foo == null) { bar(); } ``` Rule Details ------------ The `no-eq-null` rule aims reduce potential bug and unwanted behavior by ensuring that comparisons to `null` only match `null`, and not also `undefined`. As such it will flag comparisons to null when using `==` and `!=`. Examples of **incorrect** code for this rule: ``` /\*eslint no-eq-null: "error"\*/ if (foo == null) { bar(); } while (qux != null) { baz(); } ``` Examples of **correct** code for this rule: ``` /\*eslint no-eq-null: "error"\*/ if (foo === null) { bar(); } while (qux !== null) { baz(); } ``` When Not To Use It ------------------ If you want to enforce type-checking operations in general, use the more powerful [eqeqeq](no-eq-null./eqeqeq) instead. Compatibility ------------- * **JSHint**: This rule corresponds to `eqnull` rule of JSHint. Version ------- This rule was introduced in ESLint v0.0.9. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/no-eq-null.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/no-eq-null.js) eslint no-duplicate-case no-duplicate-case ================= Disallow duplicate case labels ✅ Recommended The `"extends": "eslint:recommended"` property in a [configuration file](no-duplicate-case../user-guide/configuring/configuration-files#extending-configuration-files) enables this rule If a `switch` statement has duplicate test expressions in `case` clauses, it is likely that a programmer copied a `case` clause but forgot to change the test expression. Rule Details ------------ This rule disallows duplicate test expressions in `case` clauses of `switch` statements. Examples of **incorrect** code for this rule: ``` /\*eslint no-duplicate-case: "error"\*/ var a = 1, one = 1; switch (a) { case 1: break; case 2: break; case 1: // duplicate test expression break; default: break; } switch (a) { case one: break; case 2: break; case one: // duplicate test expression break; default: break; } switch (a) { case "1": break; case "2": break; case "1": // duplicate test expression break; default: break; } ``` Examples of **correct** code for this rule: ``` /\*eslint no-duplicate-case: "error"\*/ var a = 1, one = 1; switch (a) { case 1: break; case 2: break; case 3: break; default: break; } switch (a) { case one: break; case 2: break; case 3: break; default: break; } switch (a) { case "1": break; case "2": break; case "3": break; default: break; } ``` When Not To Use It ------------------ In rare cases where identical test expressions in `case` clauses produce different values, which necessarily means that the expressions are causing and relying on side effects, you will have to disable this rule. ``` switch (a) { case i++: foo(); break; case i++: // eslint-disable-line no-duplicate-case bar(); break; } ``` Version ------- This rule was introduced in ESLint v0.17.0. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/no-duplicate-case.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/no-duplicate-case.js) eslint no-restricted-globals no-restricted-globals ===================== Disallow specified global variables Disallowing usage of specific global variables can be useful if you want to allow a set of global variables by enabling an environment, but still want to disallow some of those. For instance, early Internet Explorer versions exposed the current DOM event as a global variable `event`, but using this variable has been considered as a bad practice for a long time. Restricting this will make sure this variable isn’t used in browser code. Rule Details ------------ This rule allows you to specify global variable names that you don’t want to use in your application. Options ------- This rule takes a list of strings, where each string is a global to be restricted: ``` { "rules": { "no-restricted-globals": ["error", "event", "fdescribe"] } } ``` Alternatively, the rule also accepts objects, where the global name and an optional custom message are specified: ``` { "rules": { "no-restricted-globals": [ "error", { "name": "event", "message": "Use local parameter instead." }, { "name": "fdescribe", "message": "Do not commit fdescribe. Use describe instead." } ] } } ``` Examples of **incorrect** code for sample `"event", "fdescribe"` global variable names: ``` /\*global event, fdescribe\*/ /\*eslint no-restricted-globals: ["error", "event", "fdescribe"]\*/ function onClick() { console.log(event); } fdescribe("foo", function() { }); ``` Examples of **correct** code for a sample `"event"` global variable name: ``` /\*global event\*/ /\*eslint no-restricted-globals: ["error", "event"]\*/ import event from "event-module"; ``` ``` /\*global event\*/ /\*eslint no-restricted-globals: ["error", "event"]\*/ var event = 1; ``` Examples of **incorrect** code for a sample `"event"` global variable name, along with a custom error message: ``` /\*global event\*/ /\* eslint no-restricted-globals: ["error", { name: "event", message: "Use local parameter instead." }] \*/ function onClick() { console.log(event); // Unexpected global variable 'event'. Use local parameter instead. } ``` Related Rules ------------- * <no-restricted-properties> * <no-restricted-syntax> Version ------- This rule was introduced in ESLint v2.3.0. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/no-restricted-globals.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/no-restricted-globals.js) eslint arrow-parens arrow-parens ============ Require parentheses around arrow function arguments 🔧 Fixable Some problems reported by this rule are automatically fixable by the `--fix` [command line](arrow-parens../user-guide/command-line-interface#--fix) option Arrow functions can omit parentheses when they have exactly one parameter. In all other cases the parameter(s) must be wrapped in parentheses. This rule enforces the consistent use of parentheses in arrow functions. Rule Details ------------ This rule enforces parentheses around arrow function parameters regardless of arity. For example: ``` /\*eslint-env es6\*/ // Bad a => {} // Good (a) => {} ``` Following this style will help you find arrow functions (`=>`) which may be mistakenly included in a condition when a comparison such as `>=` was the intent. ``` /\*eslint-env es6\*/ // Bad if (a => 2) { } // Good if (a >= 2) { } ``` The rule can also be configured to discourage the use of parens when they are not required: ``` /\*eslint-env es6\*/ // Bad (a) => {} // Good a => {} ``` Options ------- This rule has a string option and an object one. String options are: * `"always"` (default) requires parens around arguments in all cases. * `"as-needed"` enforces no parens where they can be omitted. Object properties for variants of the `"as-needed"` option: * `"requireForBlockBody": true` modifies the as-needed rule in order to require parens if the function body is in an instructions block (surrounded by braces). ### always Examples of **incorrect** code for this rule with the default `"always"` option: ``` /\*eslint arrow-parens: ["error", "always"]\*/ /\*eslint-env es6\*/ a => {}; a => a; a => {'\n'}; a.then(foo => {}); a.then(foo => a); a(foo => { if (true) {} }); ``` Examples of **correct** code for this rule with the default `"always"` option: ``` /\*eslint arrow-parens: ["error", "always"]\*/ /\*eslint-env es6\*/ () => {}; (a) => {}; (a) => a; (a) => {'\n'} a.then((foo) => {}); a.then((foo) => { if (true) {} }); ``` #### If Statements One of the benefits of this option is that it prevents the incorrect use of arrow functions in conditionals: ``` /\*eslint-env es6\*/ var a = 1; var b = 2; // ... if (a => b) { console.log('bigger'); } else { console.log('smaller'); } // outputs 'bigger', not smaller as expected ``` The contents of the `if` statement is an arrow function, not a comparison. If the arrow function is intentional, it should be wrapped in parens to remove ambiguity. ``` /\*eslint-env es6\*/ var a = 1; var b = 0; // ... if ((a) => b) { console.log('truthy value returned'); } else { console.log('falsey value returned'); } // outputs 'truthy value returned' ``` The following is another example of this behavior: ``` /\*eslint-env es6\*/ var a = 1, b = 2, c = 3, d = 4; var f = a => b ? c: d; // f = ? ``` `f` is an arrow function which takes `a` as an argument and returns the result of `b ? c: d`. This should be rewritten like so: ``` /\*eslint-env es6\*/ var a = 1, b = 2, c = 3, d = 4; var f = (a) => b ? c: d; ``` ### as-needed Examples of **incorrect** code for this rule with the `"as-needed"` option: ``` /\*eslint arrow-parens: ["error", "as-needed"]\*/ /\*eslint-env es6\*/ (a) => {}; (a) => a; (a) => {'\n'}; a.then((foo) => {}); a.then((foo) => a); a((foo) => { if (true) {} }); const f = /\*\* @type {number} \*/(a) => a + a; const g = /\* comment \*/ (a) => a + a; const h = (a) /\* comment \*/ => a + a; ``` Examples of **correct** code for this rule with the `"as-needed"` option: ``` /\*eslint arrow-parens: ["error", "as-needed"]\*/ /\*eslint-env es6\*/ () => {}; a => {}; a => a; a => {'\n'}; a.then(foo => {}); a.then(foo => { if (true) {} }); (a, b, c) => a; (a = 10) => a; ([a, b]) => a; ({a, b}) => a; const f = (/\*\* @type {number} \*/a) => a + a; const g = (/\* comment \*/ a) => a + a; const h = (a /\* comment \*/) => a + a; ``` ### requireForBlockBody Examples of **incorrect** code for the `{ "requireForBlockBody": true }` option: ``` /\*eslint arrow-parens: [2, "as-needed", { "requireForBlockBody": true }]\*/ /\*eslint-env es6\*/ (a) => a; a => {}; a => {'\n'}; a.map((x) => x \* x); a.map(x => { return x \* x; }); a.then(foo => {}); ``` Examples of **correct** code for the `{ "requireForBlockBody": true }` option: ``` /\*eslint arrow-parens: [2, "as-needed", { "requireForBlockBody": true }]\*/ /\*eslint-env es6\*/ (a) => {}; (a) => {'\n'}; a => ({}); () => {}; a => a; a.then((foo) => {}); a.then((foo) => { if (true) {} }); a((foo) => { if (true) {} }); (a, b, c) => a; (a = 10) => a; ([a, b]) => a; ({a, b}) => a; ``` Version ------- This rule was introduced in ESLint v1.0.0-rc-1. Further Reading --------------- [GitHub - airbnb/javascript: JavaScript Style Guide](https://github.com/airbnb/javascript#arrows--one-arg-parens) Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/arrow-parens.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/arrow-parens.js)
programming_docs
eslint no-unsafe-finally no-unsafe-finally ================= Disallow control flow statements in `finally` blocks ✅ Recommended The `"extends": "eslint:recommended"` property in a [configuration file](no-unsafe-finally../user-guide/configuring/configuration-files#extending-configuration-files) enables this rule JavaScript suspends the control flow statements of `try` and `catch` blocks until the execution of `finally` block finishes. So, when `return`, `throw`, `break`, or `continue` is used in `finally`, control flow statements inside `try` and `catch` are overwritten, which is considered as unexpected behavior. Such as: ``` // We expect this function to return 1; (() => { try { return 1; // 1 is returned but suspended until finally block ends } catch(err) { return 2; } finally { return 3; // 3 is returned before 1, which we did not expect } })(); // > 3 ``` ``` // We expect this function to throw an error, then return (() => { try { throw new Error("Try"); // error is thrown but suspended until finally block ends } finally { return 3; // 3 is returned before the error is thrown, which we did not expect } })(); // > 3 ``` ``` // We expect this function to throw Try(...) error from the catch block (() => { try { throw new Error("Try") } catch(err) { throw err; // The error thrown from try block is caught and rethrown } finally { throw new Error("Finally"); // Finally(...) is thrown, which we did not expect } })(); // > Uncaught Error: Finally(...) ``` ``` // We expect this function to return 0 from try block. (() => { label: try { return 0; // 0 is returned but suspended until finally block ends } finally { break label; // It breaks out the try-finally block, before 0 is returned. } return 1; })(); // > 1 ``` Rule Details ------------ This rule disallows `return`, `throw`, `break`, and `continue` statements inside `finally` blocks. It allows indirect usages, such as in `function` or `class` definitions. Examples of **incorrect** code for this rule: ``` /\*eslint no-unsafe-finally: "error"\*/ let foo = function() { try { return 1; } catch(err) { return 2; } finally { return 3; } }; ``` ``` /\*eslint no-unsafe-finally: "error"\*/ let foo = function() { try { return 1; } catch(err) { return 2; } finally { throw new Error; } }; ``` Examples of **correct** code for this rule: ``` /\*eslint no-unsafe-finally: "error"\*/ let foo = function() { try { return 1; } catch(err) { return 2; } finally { console.log("hola!"); } }; ``` ``` /\*eslint no-unsafe-finally: "error"\*/ let foo = function() { try { return 1; } catch(err) { return 2; } finally { let a = function() { return "hola!"; } } }; ``` ``` /\*eslint no-unsafe-finally: "error"\*/ let foo = function(a) { try { return 1; } catch(err) { return 2; } finally { switch(a) { case 1: { console.log("hola!") break; } } } }; ``` When Not To Use It ------------------ If you want to allow control flow operations in `finally` blocks, you can turn this rule off. Version ------- This rule was introduced in ESLint v2.9.0. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/no-unsafe-finally.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/no-unsafe-finally.js) eslint space-in-brackets space-in-brackets ================= Enforces consistent spacing inside braces of object literals and brackets of array literals. (removed) This rule was **removed** in ESLint v1.0 and **replaced** by the [object-curly-spacing](space-in-bracketsobject-curly-spacing) and [array-bracket-spacing](space-in-bracketsarray-bracket-spacing) rules. While formatting preferences are very personal, a number of style guides require or disallow spaces between brackets: ``` var obj = { foo: 'bar' }; var arr = [ 'foo', 'bar' ]; foo[ 'bar' ]; var obj = {foo: 'bar'}; var arr = ['foo', 'bar']; foo['bar']; ``` Rule Details ------------ This rule aims to maintain consistency around the spacing inside of square brackets, either by disallowing spaces inside of brackets between the brackets and other tokens or enforcing spaces. Brackets that are separated from the adjacent value by a new line are excepted from this rule, as this is a common pattern. Object literals that are used as the first or last element in an array are also ignored. Options ------- There are two options for this rule: * `"always"` enforces a space inside of object and array literals * `"never"` enforces zero spaces inside of object and array literals (default) Depending on your coding conventions, you can choose either option by specifying it in your configuration: ``` "space-in-brackets": ["error", "always"] ``` ### “never” Examples of **incorrect** code for this rule with the default `"never"` option: ``` /\*eslint-env es6\*/ foo[ 'bar' ]; foo['bar' ]; var arr = [ 'foo', 'bar' ]; var arr = ['foo', 'bar' ]; var arr = [ ['foo'], 'bar']; var arr = [[ 'foo' ], 'bar']; var arr = ['foo', 'bar' ]; var obj = { 'foo': 'bar' }; var obj = {'foo': 'bar' }; var obj = { baz: {'foo': 'qux'}, bar}; var obj = {baz: { 'foo': 'qux' }, bar}; ``` Examples of **correct** code for this rule with the default `"never"` option: ``` // When options are ["error", "never"] foo['bar']; foo[ 'bar' ]; foo[ 'bar']; var arr = []; var arr = ['foo', 'bar', 'baz']; var arr = [['foo'], 'bar', 'baz']; var arr = [ 'foo', 'bar', 'baz' ]; var arr = [ 'foo', 'bar']; var obj = {'foo': 'bar'}; var obj = {'foo': {'bar': 'baz'}, 'qux': 'quxx'}; var obj = { 'foo': 'bar' }; var obj = {'foo': 'bar' }; var obj = { 'foo':'bar'}; var obj = {}; ``` ### “always” Examples of **incorrect** code for this rule with the `"always"` option: ``` /\*eslint-env es6\*/ foo['bar']; foo['bar' ]; foo[ 'bar']; var arr = ['foo', 'bar']; var arr = ['foo', 'bar' ]; var arr = [ ['foo'], 'bar' ]; var arr = ['foo', 'bar' ]; var arr = [ 'foo', 'bar']; var obj = {'foo': 'bar'}; var obj = {'foo': 'bar' }; var obj = { baz: {'foo': 'qux'}, bar}; var obj = {baz: { 'foo': 'qux' }, bar}; var obj = {'foo': 'bar' }; var obj = { 'foo':'bar'}; ``` Examples of **correct** code for this rule with the `"always"` option: ``` foo[ 'bar' ]; foo[ 'bar' ]; var arr = []; var arr = [ 'foo', 'bar', 'baz' ]; var arr = [ [ 'foo' ], 'bar', 'baz' ]; var arr = [ 'foo', 'bar', 'baz' ]; var obj = {}; var obj = { 'foo': 'bar' }; var obj = { 'foo': { 'bar': 'baz' }, 'qux': 'quxx' }; var obj = { 'foo': 'bar' }; ``` Note that `"always"` has a special case where `{}` and `[]` are not considered problems. ### Exceptions An object literal may be used as a third array item to specify spacing exceptions. These exceptions work in the context of the first option. That is, if `"always"` is set to enforce spacing and an exception is set to `false`, it will disallow spacing for cases matching the exception. Likewise, if `"never"` is set to disallow spacing and an exception is set to `true`, it will enforce spacing for cases matching the exception. You can add exceptions like so: In case of `"always"` option, set an exception to `false` to enable it: ``` "space-in-brackets": ["error", "always", { "singleValue": false, "objectsInArrays": false, "arraysInArrays": false, "arraysInObjects": false, "objectsInObjects": false, "propertyName": false }] ``` In case of `"never"` option, set an exception to `true` to enable it: ``` "space-in-brackets": ["error", "never", { "singleValue": true, "objectsInArrays": true, "arraysInArrays": true, "arraysInObjects": true, "objectsInObjects": true, "propertyName": true }] ``` The following exceptions are available: * `singleValue` sets the spacing of a single value inside of square brackets of an array. * `objectsInArrays` sets the spacings between the curly braces and square brackets of object literals that are the first or last element in an array. * `arraysInArrays` sets the spacing between the square brackets of array literals that are the first or last element in an array. * `arraysInObjects` sets the spacing between the square bracket and the curly brace of an array literal that is the last element in an object. * `objectsInObjects` sets the spacing between the curly brace of an object literal that is the last element in an object and the curly brace of the containing object. * `propertyName` sets the spacing in square brackets of computed member expressions. In each of the following examples, the `"always"` option is assumed. Examples of **incorrect** code for this rule when `"singleValue"` is set to `false`: ``` var foo = [ 'foo' ]; var foo = [ 'foo']; var foo = ['foo' ]; var foo = [ 1 ]; var foo = [ 1]; var foo = [1 ]; var foo = [ [ 1, 2 ] ]; var foo = [ { 'foo': 'bar' } ]; ``` Examples of **correct** code for this rule when `"singleValue"` is set to `false`: ``` var foo = ['foo']; var foo = [1]; var foo = [[ 1, 1 ]]; var foo = [{ 'foo': 'bar' }]; ``` Examples of **incorrect** code when `"objectsInArrays"` is set to `false`: ``` var arr = [ { 'foo': 'bar' } ]; var arr = [ { 'foo': 'bar' } ] ``` Examples of **correct** code when `"objectsInArrays"` is set to `false`: ``` var arr = [{ 'foo': 'bar' }]; var arr = [{ 'foo': 'bar' }]; ``` Examples of **incorrect** code when `"arraysInArrays"` is set to `false`: ``` var arr = [ [ 1, 2 ], 2, 3, 4 ]; var arr = [ [ 1, 2 ], 2, [ 3, 4 ] ]; ``` Examples of **correct** code when `"arraysInArrays"` is set to `false`: ``` var arr = [[ 1, 2 ], 2, 3, 4 ]; var arr = [[ 1, 2 ], 2, [ 3, 4 ]]; ``` Examples of **incorrect** code when `"arraysInObjects"` is set to `false`: ``` var obj = { "foo": [ 1, 2 ] }; var obj = { "foo": [ "baz", "bar" ] }; ``` Examples of **correct** code when `"arraysInObjects"` is set to `false`: ``` var obj = { "foo": [ 1, 2 ]}; var obj = { "foo": [ "baz", "bar" ]}; ``` Examples of **incorrect** code when `"objectsInObjects"` is set to `false`: ``` var obj = { "foo": { "baz": 1, "bar": 2 } }; var obj = { "foo": [ "baz", "bar" ], "qux": { "baz": 1, "bar": 2 } }; ``` Examples of **correct** code when `"objectsInObjects"` is set to `false`: ``` var obj = { "foo": { "baz": 1, "bar": 2 }}; var obj = { "foo": [ "baz", "bar" ], "qux": { "baz": 1, "bar": 2 }}; ``` Examples of **incorrect** code when `"propertyName"` is set to `false`: ``` var foo = obj[ 1 ]; var foo = obj[ bar ]; ``` Examples of **correct** code when `"propertyName"` is set to `false`: ``` var foo = obj[bar]; var foo = obj[0, 1]; ``` When Not To Use It ------------------ You can turn this rule off if you are not concerned with the consistency of spacing between brackets. Related Rules ------------- * <array-bracket-spacing> * <object-curly-spacing> * <space-in-parens> * <computed-property-spacing> Version ------- This rule was introduced in ESLint v0.4.1 and removed in v1.0.0-rc-1. eslint no-undef no-undef ======== Disallow the use of undeclared variables unless mentioned in `/*global */` comments ✅ Recommended The `"extends": "eslint:recommended"` property in a [configuration file](no-undef../user-guide/configuring/configuration-files#extending-configuration-files) enables this rule This rule can help you locate potential ReferenceErrors resulting from misspellings of variable and parameter names, or accidental implicit globals (for example, from forgetting the `var` keyword in a `for` loop initializer). Rule Details ------------ Any reference to an undeclared variable causes a warning, unless the variable is explicitly mentioned in a `/*global ...*/` comment, or specified in the [`globals` key in the configuration file](no-undef../user-guide/configuring/language-options#using-configuration-files-1). A common use case for these is if you intentionally use globals that are defined elsewhere (e.g. in a script sourced from HTML). Examples of **incorrect** code for this rule: ``` /\*eslint no-undef: "error"\*/ var foo = someFunction(); var bar = a + 1; ``` Examples of **correct** code for this rule with `global` declaration: ``` /\*global someFunction, a\*/ /\*eslint no-undef: "error"\*/ var foo = someFunction(); var bar = a + 1; ``` Note that this rule does not disallow assignments to read-only global variables. See [no-global-assign](no-undefno-global-assign) if you also want to disallow those assignments. This rule also does not disallow redeclarations of global variables. See [no-redeclare](no-undefno-redeclare) if you also want to disallow those redeclarations. Options ------- * `typeof` set to true will warn for variables used inside typeof check (Default false). ### typeof Examples of **correct** code for the default `{ "typeof": false }` option: ``` /\*eslint no-undef: "error"\*/ if (typeof UndefinedIdentifier === "undefined") { // do something ... } ``` You can use this option if you want to prevent `typeof` check on a variable which has not been declared. Examples of **incorrect** code for the `{ "typeof": true }` option: ``` /\*eslint no-undef: ["error", { "typeof": true }] \*/ if(typeof a === "string"){} ``` Examples of **correct** code for the `{ "typeof": true }` option with `global` declaration: ``` /\*global a\*/ /\*eslint no-undef: ["error", { "typeof": true }] \*/ if(typeof a === "string"){} ``` Environments ------------ For convenience, ESLint provides shortcuts that pre-define global variables exposed by popular libraries and runtime environments. This rule supports these environments, as listed in [Specifying Environments](no-undef../user-guide/configuring/language-options#specifying-environments). A few examples are given below. ### browser Examples of **correct** code for this rule with `browser` environment: ``` /\*eslint no-undef: "error"\*/ /\*eslint-env browser\*/ setTimeout(function() { alert("Hello"); }); ``` ### Node.js Examples of **correct** code for this rule with `node` environment: ``` /\*eslint no-undef: "error"\*/ /\*eslint-env node\*/ var fs = require("fs"); module.exports = function() { console.log(fs); }; ``` When Not To Use It ------------------ If explicit declaration of global variables is not to your taste. Compatibility ------------- This rule provides compatibility with treatment of global variables in [JSHint](http://jshint.com/) and [JSLint](http://www.jslint.com). Related Rules ------------- * <no-global-assign> * <no-redeclare> Version ------- This rule was introduced in ESLint v0.0.9. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/no-undef.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/no-undef.js) eslint no-sequences no-sequences ============ Disallow comma operators The comma operator includes multiple expressions where only one is expected. It evaluates each operand from left to right and returns the value of the last operand. However, this frequently obscures side effects, and its use is often an accident. Here are some examples of sequences: ``` var a = (3, 5); // a = 5 a = b += 5, a + b; while (a = next(), a && a.length); (0, eval)("doSomething();"); ``` Rule Details ------------ This rule forbids the use of the comma operator, with the following exceptions: * In the initialization or update portions of a `for` statement. * By default, if the expression sequence is explicitly wrapped in parentheses. This exception can be removed with the `allowInParentheses` option. Examples of **incorrect** code for this rule: ``` /\*eslint no-sequences: "error"\*/ foo = doSomething(), val; 0, eval("doSomething();"); do {} while (doSomething(), !!test); for (; doSomething(), !!test; ); if (doSomething(), !!test); switch (val = foo(), val) {} while (val = foo(), val < 42); with (doSomething(), val) {} ``` Examples of **correct** code for this rule: ``` /\*eslint no-sequences: "error"\*/ foo = (doSomething(), val); (0, eval)("doSomething();"); do {} while ((doSomething(), !!test)); for (i = 0, j = 10; i < j; i++, j--); if ((doSomething(), !!test)); switch ((val = foo(), val)) {} while ((val = foo(), val < 42)); with ((doSomething(), val)) {} ``` ### Note about arrow function bodies If an arrow function body is a statement rather than a block, and that statement contains a sequence, you need to use double parentheses around the statement to indicate that the sequence is intentional. Examples of **incorrect** code for arrow functions: ``` /\*eslint no-sequences: "error"\*/ const foo = (val) => (console.log('bar'), val); const foo = () => ((bar = 123), 10); const foo = () => { return (bar = 123), 10 } ``` Examples of **correct** code for arrow functions: ``` /\*eslint no-sequences: "error"\*/ const foo = (val) => ((console.log('bar'), val)); const foo = () => (((bar = 123), 10)); const foo = () => { return ((bar = 123), 10) } ``` Options ------- This rule takes one option, an object, with the following properties: * `"allowInParentheses"`: If set to `true` (default), this rule allows expression sequences that are explicitly wrapped in parentheses. ### allowInParentheses Examples of **incorrect** code for this rule with the `{ "allowInParentheses": false }` option: ``` /\*eslint no-sequences: ["error", { "allowInParentheses": false }]\*/ foo = (doSomething(), val); (0, eval)("doSomething();"); do {} while ((doSomething(), !!test)); for (; (doSomething(), !!test); ); if ((doSomething(), !!test)); switch ((val = foo(), val)) {} while ((val = foo(), val < 42)); with ((doSomething(), val)) {} const foo = (val) => ((console.log('bar'), val)); ``` Examples of **correct** code for this rule with the `{ "allowInParentheses": false }` option: ``` /\*eslint no-sequences: ["error", { "allowInParentheses": false }]\*/ for (i = 0, j = 10; i < j; i++, j--); ``` When Not To Use It ------------------ Disable this rule if sequence expressions with the comma operator are acceptable. Another case is where you might want to report all usages of the comma operator, even in a for loop. You can achieve this using rule `no-restricted-syntax`: ``` { "rules": { "no-restricted-syntax": ["error", "SequenceExpression"] } } ``` Version ------- This rule was introduced in ESLint v0.5.1. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/no-sequences.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/no-sequences.js) eslint eol-last eol-last ======== Require or disallow newline at the end of files 🔧 Fixable Some problems reported by this rule are automatically fixable by the `--fix` [command line](eol-last../user-guide/command-line-interface#--fix) option Trailing newlines in non-empty files are a common UNIX idiom. Benefits of trailing newlines include the ability to concatenate or append to files as well as output files to the terminal without interfering with shell prompts. Rule Details ------------ This rule enforces at least one newline (or absence thereof) at the end of non-empty files. Prior to v0.16.0 this rule also enforced that there was only a single line at the end of the file. If you still want this behavior, consider enabling [no-multiple-empty-lines](eol-lastno-multiple-empty-lines) with `maxEOF` and/or [no-trailing-spaces](eol-lastno-trailing-spaces). Examples of **incorrect** code for this rule: ``` /\*eslint eol-last: ["error", "always"]\*/ function doSomething() { var foo = 2; } ``` Examples of **correct** code for this rule: ``` /\*eslint eol-last: ["error", "always"]\*/ function doSomething() { var foo = 2; }\n ``` Options ------- This rule has a string option: * `"always"` (default) enforces that files end with a newline (LF) * `"never"` enforces that files do not end with a newline * `"unix"` (deprecated) is identical to “always” * `"windows"` (deprecated) is identical to “always”, but will use a CRLF character when autofixing **Deprecated:** The options `"unix"` and `"windows"` are deprecated. If you need to enforce a specific linebreak style, use this rule in conjunction with `linebreak-style`. Version ------- This rule was introduced in ESLint v0.7.1. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/eol-last.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/eol-last.js)
programming_docs
eslint no-extra-boolean-cast no-extra-boolean-cast ===================== Disallow unnecessary boolean casts ✅ Recommended The `"extends": "eslint:recommended"` property in a [configuration file](no-extra-boolean-cast../user-guide/configuring/configuration-files#extending-configuration-files) enables this rule 🔧 Fixable Some problems reported by this rule are automatically fixable by the `--fix` [command line](no-extra-boolean-cast../user-guide/command-line-interface#--fix) option In contexts such as an `if` statement’s test where the result of the expression will already be coerced to a Boolean, casting to a Boolean via double negation (`!!`) or a `Boolean` call is unnecessary. For example, these `if` statements are equivalent: ``` if (!!foo) { // ... } if (Boolean(foo)) { // ... } if (foo) { // ... } ``` Rule Details ------------ This rule disallows unnecessary boolean casts. Examples of **incorrect** code for this rule: ``` /\*eslint no-extra-boolean-cast: "error"\*/ var foo = !!!bar; var foo = !!bar ? baz : bat; var foo = Boolean(!!bar); var foo = new Boolean(!!bar); if (!!foo) { // ... } if (Boolean(foo)) { // ... } while (!!foo) { // ... } do { // ... } while (Boolean(foo)); for (; !!foo; ) { // ... } ``` Examples of **correct** code for this rule: ``` /\*eslint no-extra-boolean-cast: "error"\*/ var foo = !!bar; var foo = Boolean(bar); function foo() { return !!bar; } var foo = bar ? !!baz : !!bat; ``` Options ------- This rule has an object option: * `"enforceForLogicalOperands"` when set to `true`, in addition to checking default contexts, checks whether the extra boolean cast is contained within a logical expression. Default is `false`, meaning that this rule by default does not warn about extra booleans cast inside logical expression. ### enforceForLogicalOperands Examples of **incorrect** code for this rule with `"enforceForLogicalOperands"` option set to `true`: ``` /\*eslint no-extra-boolean-cast: ["error", {"enforceForLogicalOperands": true}]\*/ if (!!foo || bar) { //... } while (!!foo && bar) { //... } if ((!!foo || bar) && baz) { //... } foo && Boolean(bar) ? baz : bat var foo = new Boolean(!!bar || baz) ``` Examples of **correct** code for this rule with `"enforceForLogicalOperands"` option set to `true`: ``` /\*eslint no-extra-boolean-cast: ["error", {"enforceForLogicalOperands": true}]\*/ if (foo || bar) { //... } while (foo && bar) { //... } if ((foo || bar) && baz) { //... } foo && bar ? baz : bat var foo = new Boolean(bar || baz) var foo = !!bar || baz; ``` Version ------- This rule was introduced in ESLint v0.4.0. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/no-extra-boolean-cast.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/no-extra-boolean-cast.js) eslint no-const-assign no-const-assign =============== Disallow reassigning `const` variables ✅ Recommended The `"extends": "eslint:recommended"` property in a [configuration file](no-const-assign../user-guide/configuring/configuration-files#extending-configuration-files) enables this rule We cannot modify variables that are declared using `const` keyword. It will raise a runtime error. Under non ES2015 environment, it might be ignored merely. Rule Details ------------ This rule is aimed to flag modifying variables that are declared using `const` keyword. Examples of **incorrect** code for this rule: ``` /\*eslint no-const-assign: "error"\*/ /\*eslint-env es6\*/ const a = 0; a = 1; ``` ``` /\*eslint no-const-assign: "error"\*/ /\*eslint-env es6\*/ const a = 0; a += 1; ``` ``` /\*eslint no-const-assign: "error"\*/ /\*eslint-env es6\*/ const a = 0; ++a; ``` Examples of **correct** code for this rule: ``` /\*eslint no-const-assign: "error"\*/ /\*eslint-env es6\*/ const a = 0; console.log(a); ``` ``` /\*eslint no-const-assign: "error"\*/ /\*eslint-env es6\*/ for (const a in [1, 2, 3]) { // `a` is re-defined (not modified) on each loop step. console.log(a); } ``` ``` /\*eslint no-const-assign: "error"\*/ /\*eslint-env es6\*/ for (const a of [1, 2, 3]) { // `a` is re-defined (not modified) on each loop step. console.log(a); } ``` When Not To Use It ------------------ If you don’t want to be notified about modifying variables that are declared using `const` keyword, you can safely disable this rule. Version ------- This rule was introduced in ESLint v1.0.0-rc-1. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/no-const-assign.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/no-const-assign.js) eslint no-invalid-this no-invalid-this =============== Disallow use of `this` in contexts where the value of `this` is `undefined` Under the strict mode, `this` keywords outside of classes or class-like objects might be `undefined` and raise a `TypeError`. Rule Details ------------ This rule aims to flag usage of `this` keywords in contexts where the value of `this` is `undefined`. Top-level `this` in scripts is always considered valid because it refers to the global object regardless of the strict mode. Top-level `this` in ECMAScript modules is always considered invalid because its value is `undefined`. For `this` inside functions, this rule basically checks whether or not the function containing `this` keyword is a constructor or a method. Note that arrow functions have lexical `this`, and that therefore this rule checks their enclosing contexts. This rule judges from following conditions whether or not the function is a constructor: * The name of the function starts with uppercase. * The function is assigned to a variable which starts with an uppercase letter. * The function is a constructor of ES2015 Classes. This rule judges from following conditions whether or not the function is a method: * The function is on an object literal. * The function is assigned to a property. * The function is a method/getter/setter of ES2015 Classes. And this rule allows `this` keywords in functions below: * The `call/apply/bind` method of the function is called directly. * The function is a callback of array methods (such as `.forEach()`) if `thisArg` is given. * The function has `@this` tag in its JSDoc comment. And this rule always allows `this` keywords in the following contexts: * At the top level of scripts. * In class field initializers. * In class static blocks. Otherwise are considered problems. This rule applies **only** in strict mode. With `"parserOptions": { "sourceType": "module" }` in the ESLint configuration, your code is in strict mode even without a `"use strict"` directive. Examples of **incorrect** code for this rule in strict mode: ``` /\*eslint no-invalid-this: "error"\*/ /\*eslint-env es6\*/ "use strict"; (function() { this.a = 0; baz(() => this); })(); function foo() { this.a = 0; baz(() => this); } var foo = function() { this.a = 0; baz(() => this); }; foo(function() { this.a = 0; baz(() => this); }); var obj = { aaa: function() { return function foo() { // There is in a method `aaa`, but `foo` is not a method. this.a = 0; baz(() => this); }; } }; foo.forEach(function() { this.a = 0; baz(() => this); }); ``` Examples of **correct** code for this rule in strict mode: ``` /\*eslint no-invalid-this: "error"\*/ /\*eslint-env es6\*/ "use strict"; this.a = 0; baz(() => this); function Foo() { // OK, this is in a legacy style constructor. this.a = 0; baz(() => this); } class Foo { constructor() { // OK, this is in a constructor. this.a = 0; baz(() => this); } } var obj = { foo: function foo() { // OK, this is in a method (this function is on object literal). this.a = 0; } }; var obj = { foo() { // OK, this is in a method (this function is on object literal). this.a = 0; } }; var obj = { get foo() { // OK, this is in a method (this function is on object literal). return this.a; } }; var obj = Object.create(null, { foo: {value: function foo() { // OK, this is in a method (this function is on object literal). this.a = 0; }} }); Object.defineProperty(obj, "foo", { value: function foo() { // OK, this is in a method (this function is on object literal). this.a = 0; } }); Object.defineProperties(obj, { foo: {value: function foo() { // OK, this is in a method (this function is on object literal). this.a = 0; }} }); function Foo() { this.foo = function foo() { // OK, this is in a method (this function assigns to a property). this.a = 0; baz(() => this); }; } obj.foo = function foo() { // OK, this is in a method (this function assigns to a property). this.a = 0; }; Foo.prototype.foo = function foo() { // OK, this is in a method (this function assigns to a property). this.a = 0; }; class Foo { // OK, this is in a class field initializer. a = this.b; // OK, static initializers also have valid this. static a = this.b; foo() { // OK, this is in a method. this.a = 0; baz(() => this); } static foo() { // OK, this is in a method (static methods also have valid this). this.a = 0; baz(() => this); } static { // OK, static blocks also have valid this. this.a = 0; baz(() => this); } } var foo = (function foo() { // OK, the `bind` method of this function is called directly. this.a = 0; }).bind(obj); foo.forEach(function() { // OK, `thisArg` of `.forEach()` is given. this.a = 0; baz(() => this); }, thisArg); /\*\* @this Foo \*/ function foo() { // OK, this function has a `@this` tag in its JSDoc comment. this.a = 0; } ``` Options ------- This rule has an object option, with one option: * `"capIsConstructor": false` (default `true`) disables the assumption that a function which name starts with an uppercase is a constructor. ### capIsConstructor By default, this rule always allows the use of `this` in functions which name starts with an uppercase and anonymous functions that are assigned to a variable which name starts with an uppercase, assuming that those functions are used as constructor functions. Set `"capIsConstructor"` to `false` if you want those functions to be treated as ‘regular’ functions. Examples of **incorrect** code for this rule with `"capIsConstructor"` option set to `false`: ``` /\*eslint no-invalid-this: ["error", { "capIsConstructor": false }]\*/ "use strict"; function Foo() { this.a = 0; } var bar = function Foo() { this.a = 0; } var Bar = function() { this.a = 0; }; Baz = function() { this.a = 0; }; ``` Examples of **correct** code for this rule with `"capIsConstructor"` option set to `false`: ``` /\*eslint no-invalid-this: ["error", { "capIsConstructor": false }]\*/ "use strict"; obj.Foo = function Foo() { // OK, this is in a method. this.a = 0; }; ``` When Not To Use It ------------------ If you don’t want to be notified about usage of `this` keyword outside of classes or class-like objects, you can safely disable this rule. Version ------- This rule was introduced in ESLint v1.0.0-rc-2. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/no-invalid-this.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/no-invalid-this.js) eslint comma-spacing comma-spacing ============= Enforce consistent spacing before and after commas 🔧 Fixable Some problems reported by this rule are automatically fixable by the `--fix` [command line](comma-spacing../user-guide/command-line-interface#--fix) option Spacing around commas improves readability of a list of items. Although most of the style guidelines for languages prescribe adding a space after a comma and not before it, it is subjective to the preferences of a project. ``` var foo = 1, bar = 2; var foo = 1 ,bar = 2; ``` Rule Details ------------ This rule enforces consistent spacing before and after commas in variable declarations, array literals, object literals, function parameters, and sequences. This rule does not apply in either of the following cases: * between two commas * between opening bracket `[` and comma, to avoid conflicts with the [`array-bracket-spacing`](comma-spacingarray-bracket-spacing) rule * between comma and closing bracket `]`, to avoid conflicts with the [`array-bracket-spacing`](comma-spacingarray-bracket-spacing) rule * between comma and closing brace `}`, to avoid conflicts with the [`object-curly-spacing`](comma-spacingobject-curly-spacing) rule * between comma and closing parentheses `)`, to avoid conflicts with the [`space-in-parens`](comma-spacingspace-in-parens) rule Options ------- This rule has an object option: * `"before": false` (default) disallows spaces before commas * `"before": true` requires one or more spaces before commas * `"after": true` (default) requires one or more spaces after commas * `"after": false` disallows spaces after commas ### after Examples of **incorrect** code for this rule with the default `{ "before": false, "after": true }` options: ``` /\*eslint comma-spacing: ["error", { "before": false, "after": true }]\*/ var foo = 1 ,bar = 2; var arr = [1 , 2]; var obj = {"foo": "bar" ,"baz": "qur"}; foo(a ,b); new Foo(a ,b); function foo(a ,b){} a ,b ``` Examples of **correct** code for this rule with the default `{ "before": false, "after": true }` options: ``` /\*eslint comma-spacing: ["error", { "before": false, "after": true }]\*/ var foo = 1, bar = 2 , baz = 3; var arr = [1, 2]; var arr = [1,, 3] var obj = {"foo": "bar", "baz": "qur"}; foo(a, b); new Foo(a, b); function foo(a, b){} a, b ``` Additional examples of **correct** code for this rule with the default `{ "before": false, "after": true }` options: ``` /\*eslint comma-spacing: ["error", { "before": false, "after": true }]\*/ // this rule does not enforce spacing between two commas var arr = [ ,, , , ]; // this rule does not enforce spacing after `[` and before `]` var arr = [,]; var arr = [ , ]; var arr = [a, b,]; [,] = arr; [ , ] = arr; [a, b,] = arr; // this rule does not enforce spacing before `}` var obj = {x, y,}; var {z, q,} = obj; import {foo, bar,} from "mod"; // this rule does not enforce spacing before `)` foo(a, b,) ``` ### before Examples of **incorrect** code for this rule with the `{ "before": true, "after": false }` options: ``` /\*eslint comma-spacing: ["error", { "before": true, "after": false }]\*/ var foo = 1, bar = 2; var arr = [1 , 2]; var obj = {"foo": "bar", "baz": "qur"}; new Foo(a,b); function foo(a,b){} a, b ``` Examples of **correct** code for this rule with the `{ "before": true, "after": false }` options: ``` /\*eslint comma-spacing: ["error", { "before": true, "after": false }]\*/ var foo = 1 ,bar = 2 , baz = true; var arr = [1 ,2]; var arr = [1 ,,3] var obj = {"foo": "bar" ,"baz": "qur"}; foo(a ,b); new Foo(a ,b); function foo(a ,b){} a ,b ``` When Not To Use It ------------------ If your project will not be following a consistent comma-spacing pattern, turn this rule off. Related Rules ------------- * <array-bracket-spacing> * <comma-style> * <object-curly-spacing> * <space-in-brackets> * <space-in-parens> * <space-infix-ops> * <space-after-keywords> * <space-unary-ops> * <space-return-throw-case> Version ------- This rule was introduced in ESLint v0.9.0. Further Reading --------------- [Code Conventions for the JavaScript Programming Language](https://www.crockford.com/code.html) [Dojo Style Guide — The Dojo Toolkit - Reference Guide](https://dojotoolkit.org/reference-guide/1.9/developer/styleguide.html) Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/comma-spacing.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/comma-spacing.js) eslint no-ex-assign no-ex-assign ============ Disallow reassigning exceptions in `catch` clauses ✅ Recommended The `"extends": "eslint:recommended"` property in a [configuration file](no-ex-assign../user-guide/configuring/configuration-files#extending-configuration-files) enables this rule If a `catch` clause in a `try` statement accidentally (or purposely) assigns another value to the exception parameter, it is impossible to refer to the error from that point on. Since there is no `arguments` object to offer alternative access to this data, assignment of the parameter is absolutely destructive. Rule Details ------------ This rule disallows reassigning exceptions in `catch` clauses. Examples of **incorrect** code for this rule: ``` /\*eslint no-ex-assign: "error"\*/ try { // code } catch (e) { e = 10; } ``` Examples of **correct** code for this rule: ``` /\*eslint no-ex-assign: "error"\*/ try { // code } catch (e) { var foo = 10; } ``` Version ------- This rule was introduced in ESLint v0.0.9. Further Reading --------------- [The](https://bocoup.com/blog/the-catch-with-try-catch) Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/no-ex-assign.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/no-ex-assign.js) eslint no-unneeded-ternary no-unneeded-ternary =================== Disallow ternary operators when simpler alternatives exist 🔧 Fixable Some problems reported by this rule are automatically fixable by the `--fix` [command line](no-unneeded-ternary../user-guide/command-line-interface#--fix) option It’s a common mistake in JavaScript to use a conditional expression to select between two Boolean values instead of using ! to convert the test to a Boolean. Here are some examples: ``` // Bad var isYes = answer === 1 ? true : false; // Good var isYes = answer === 1; // Bad var isNo = answer === 1 ? false : true; // Good var isNo = answer !== 1; ``` Another common mistake is using a single variable as both the conditional test and the consequent. In such cases, the logical `OR` can be used to provide the same functionality. Here is an example: ``` // Bad foo(bar ? bar : 1); // Good foo(bar || 1); ``` Rule Details ------------ This rule disallow ternary operators when simpler alternatives exist. Examples of **incorrect** code for this rule: ``` /\*eslint no-unneeded-ternary: "error"\*/ var a = x === 2 ? true : false; var a = x ? true : false; ``` Examples of **correct** code for this rule: ``` /\*eslint no-unneeded-ternary: "error"\*/ var a = x === 2 ? "Yes" : "No"; var a = x !== false; var a = x ? "Yes" : "No"; var a = x ? y : x; f(x ? x : 1); // default assignment - would be disallowed if defaultAssignment option set to false. See option details below. ``` Options ------- This rule has an object option: * `"defaultAssignment": true` (default) allows the conditional expression as a default assignment pattern * `"defaultAssignment": false` disallows the conditional expression as a default assignment pattern ### defaultAssignment When set to `true`, which it is by default, The defaultAssignment option allows expressions of the form `x ? x : expr` (where `x` is any identifier and `expr` is any expression). Examples of additional **incorrect** code for this rule with the `{ "defaultAssignment": false }` option: ``` /\*eslint no-unneeded-ternary: ["error", { "defaultAssignment": false }]\*/ var a = x ? x : 1; f(x ? x : 1); ``` Note that `defaultAssignment: false` still allows expressions of the form `x ? expr : x` (where the identifier is on the right hand side of the ternary). When Not To Use It ------------------ You can turn this rule off if you are not concerned with unnecessary complexity in conditional expressions. Related Rules ------------- * <no-ternary> * <no-nested-ternary> Version ------- This rule was introduced in ESLint v0.21.0. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/no-unneeded-ternary.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/no-unneeded-ternary.js)
programming_docs
eslint no-bitwise no-bitwise ========== Disallow bitwise operators The use of bitwise operators in JavaScript is very rare and often `&` or `|` is simply a mistyped `&&` or `||`, which will lead to unexpected behavior. ``` var x = y | z; ``` Rule Details ------------ This rule disallows bitwise operators. Examples of **incorrect** code for this rule: ``` /\*eslint no-bitwise: "error"\*/ var x = y | z; var x = y & z; var x = y ^ z; var x = ~ z; var x = y << z; var x = y >> z; var x = y >>> z; x |= y; x &= y; x ^= y; x <<= y; x >>= y; x >>>= y; ``` Examples of **correct** code for this rule: ``` /\*eslint no-bitwise: "error"\*/ var x = y || z; var x = y && z; var x = y > z; var x = y < z; x += y; ``` Options ------- This rule has an object option: * `"allow"`: Allows a list of bitwise operators to be used as exceptions. * `"int32Hint"`: Allows the use of bitwise OR in `|0` pattern for type casting. ### allow Examples of **correct** code for this rule with the `{ "allow": ["~"] }` option: ``` /\*eslint no-bitwise: ["error", { "allow": ["~"] }] \*/ ~[1,2,3].indexOf(1) === -1; ``` ### int32Hint Examples of **correct** code for this rule with the `{ "int32Hint": true }` option: ``` /\*eslint no-bitwise: ["error", { "int32Hint": true }] \*/ var b = a|0; ``` Version ------- This rule was introduced in ESLint v0.0.2. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/no-bitwise.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/no-bitwise.js) eslint func-style func-style ========== Enforce the consistent use of either `function` declarations or expressions There are two ways of defining functions in JavaScript: `function` declarations and `function` expressions. Declarations contain the `function` keyword first, followed by a name and then its arguments and the function body, for example: ``` function doSomething() { // ... } ``` Equivalent function expressions begin with the `var` keyword, followed by a name and then the function itself, such as: ``` var doSomething = function() { // ... }; ``` The primary difference between `function` declarations and `function expressions` is that declarations are *hoisted* to the top of the scope in which they are defined, which allows you to write code that uses the function before its declaration. For example: ``` doSomething(); function doSomething() { // ... } ``` Although this code might seem like an error, it actually works fine because JavaScript engines hoist the `function` declarations to the top of the scope. That means this code is treated as if the declaration came before the invocation. For `function` expressions, you must define the function before it is used, otherwise it causes an error. Example: ``` doSomething(); // error! var doSomething = function() { // ... }; ``` In this case, `doSomething()` is undefined at the time of invocation and so causes a runtime error. Due to these different behaviors, it is common to have guidelines as to which style of function should be used. There is really no correct or incorrect choice here, it is just a preference. Rule Details ------------ This rule enforces a particular type of `function` style throughout a JavaScript file, either declarations or expressions. You can specify which you prefer in the configuration. Options ------- This rule has a string option: * `"expression"` (default) requires the use of function expressions instead of function declarations * `"declaration"` requires the use of function declarations instead of function expressions This rule has an object option for an exception: * `"allowArrowFunctions"`: `true` (default `false`) allows the use of arrow functions. This option applies only when the string option is set to `"declaration"` (arrow functions are always allowed when the string option is set to `"expression"`, regardless of this option) ### expression Examples of **incorrect** code for this rule with the default `"expression"` option: ``` /\*eslint func-style: ["error", "expression"]\*/ function foo() { // ... } ``` Examples of **correct** code for this rule with the default `"expression"` option: ``` /\*eslint func-style: ["error", "expression"]\*/ var foo = function() { // ... }; var foo = () => {}; // allowed as allowArrowFunctions : false is applied only for declaration ``` ### declaration Examples of **incorrect** code for this rule with the `"declaration"` option: ``` /\*eslint func-style: ["error", "declaration"]\*/ var foo = function() { // ... }; var foo = () => {}; ``` Examples of **correct** code for this rule with the `"declaration"` option: ``` /\*eslint func-style: ["error", "declaration"]\*/ function foo() { // ... } // Methods (functions assigned to objects) are not checked by this rule SomeObject.foo = function() { // ... }; ``` ### allowArrowFunctions Examples of additional **correct** code for this rule with the `"declaration", { "allowArrowFunctions": true }` options: ``` /\*eslint func-style: ["error", "declaration", { "allowArrowFunctions": true }]\*/ var foo = () => {}; ``` When Not To Use It ------------------ If you want to allow developers to each decide how they want to write functions on their own, then you can disable this rule. Version ------- This rule was introduced in ESLint v0.2.0. Further Reading --------------- [JavaScript Scoping and Hoisting](https://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html) Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/func-style.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/func-style.js) eslint no-misleading-character-class no-misleading-character-class ============================= Disallow characters which are made with multiple code points in character class syntax ✅ Recommended The `"extends": "eslint:recommended"` property in a [configuration file](no-misleading-character-class../user-guide/configuring/configuration-files#extending-configuration-files) enables this rule 💡 hasSuggestions Some problems reported by this rule are manually fixable by editor [suggestions](no-misleading-character-class../developer-guide/working-with-rules#providing-suggestions) Unicode includes the characters which are made with multiple code points. RegExp character class syntax (`/[abc]/`) cannot handle characters which are made by multiple code points as a character; those characters will be dissolved to each code point. For example, `❇️` is made by `❇` (`U+2747`) and VARIATION SELECTOR-16 (`U+FE0F`). If this character is in RegExp character class, it will match to either `❇` (`U+2747`) or VARIATION SELECTOR-16 (`U+FE0F`) rather than `❇️`. This rule reports the regular expressions which include multiple code point characters in character class syntax. This rule considers the following characters as multiple code point characters. **A character with combining characters:** The combining characters are characters which belong to one of `Mc`, `Me`, and `Mn` [Unicode general categories](http://www.unicode.org/L2/L1999/UnicodeData.html#General%20Category). ``` /^[Á]$/u.test("Á") //→ false /^[❇️]$/u.test("❇️") //→ false ``` **A character with Emoji modifiers:** ``` /^[👶🏻]$/u.test("👶🏻") //→ false /^[👶🏽]$/u.test("👶🏽") //→ false ``` **A pair of regional indicator symbols:** ``` /^[🇯🇵]$/u.test("🇯🇵") //→ false ``` **Characters that ZWJ joins:** ``` /^[👨‍👩‍👦]$/u.test("👨‍👩‍👦") //→ false ``` **A surrogate pair without Unicode flag:** ``` /^[👍]$/.test("👍") //→ false // Surrogate pair is OK if with u flag. /^[👍]$/u.test("👍") //→ true ``` Rule Details ------------ This rule reports the regular expressions which include multiple code point characters in character class syntax. Examples of **incorrect** code for this rule: ``` /\*eslint no-misleading-character-class: error \*/ /^[Á]$/u /^[❇️]$/u /^[👶🏻]$/u /^[🇯🇵]$/u /^[👨‍👩‍👦]$/u /^[👍]$/ ``` Examples of **correct** code for this rule: ``` /\*eslint no-misleading-character-class: error \*/ /^[abc]$/ /^[👍]$/u ``` When Not To Use It ------------------ You can turn this rule off if you don’t want to check RegExp character class syntax for multiple code point characters. Version ------- This rule was introduced in ESLint v5.3.0. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/no-misleading-character-class.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/no-misleading-character-class.js) eslint no-extra-bind no-extra-bind ============= Disallow unnecessary calls to `.bind()` 🔧 Fixable Some problems reported by this rule are automatically fixable by the `--fix` [command line](no-extra-bind../user-guide/command-line-interface#--fix) option The `bind()` method is used to create functions with specific `this` values and, optionally, binds arguments to specific values. When used to specify the value of `this`, it’s important that the function actually uses `this` in its function body. For example: ``` var boundGetName = (function getName() { return this.name; }).bind({ name: "ESLint" }); console.log(boundGetName()); // "ESLint" ``` This code is an example of a good use of `bind()` for setting the value of `this`. Sometimes during the course of code maintenance, the `this` value is removed from the function body. In that case, you can end up with a call to `bind()` that doesn’t accomplish anything: ``` // useless bind var boundGetName = (function getName() { return "ESLint"; }).bind({ name: "ESLint" }); console.log(boundGetName()); // "ESLint" ``` In this code, the reference to `this` has been removed but `bind()` is still used. In this case, the `bind()` is unnecessary overhead (and a performance hit) and can be safely removed. Rule Details ------------ This rule is aimed at avoiding the unnecessary use of `bind()` and as such will warn whenever an immediately-invoked function expression (IIFE) is using `bind()` and doesn’t have an appropriate `this` value. This rule won’t flag usage of `bind()` that includes function argument binding. **Note:** Arrow functions can never have their `this` value set using `bind()`. This rule flags all uses of `bind()` with arrow functions as a problem Examples of **incorrect** code for this rule: ``` /\*eslint no-extra-bind: "error"\*/ /\*eslint-env es6\*/ var x = function () { foo(); }.bind(bar); var x = (() => { foo(); }).bind(bar); var x = (() => { this.foo(); }).bind(bar); var x = function () { (function () { this.foo(); }()); }.bind(bar); var x = function () { function foo() { this.bar(); } }.bind(baz); ``` Examples of **correct** code for this rule: ``` /\*eslint no-extra-bind: "error"\*/ var x = function () { this.foo(); }.bind(bar); var x = function (a) { return a + 1; }.bind(foo, bar); ``` When Not To Use It ------------------ If you are not concerned about unnecessary calls to `bind()`, you can safely disable this rule. Version ------- This rule was introduced in ESLint v0.8.0. Further Reading --------------- [Function.prototype.bind() - JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind) [Understanding JavaScript Bind () — Smashing Magazine](https://www.smashingmagazine.com/2014/01/understanding-javascript-function-prototype-bind/) Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/no-extra-bind.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/no-extra-bind.js) eslint comma-dangle comma-dangle ============ Require or disallow trailing commas 🔧 Fixable Some problems reported by this rule are automatically fixable by the `--fix` [command line](comma-dangle../user-guide/command-line-interface#--fix) option Trailing commas in object literals are valid according to the ECMAScript 5 (and ECMAScript 3!) spec. However, IE8 (when not in IE8 document mode) and below will throw an error when it encounters trailing commas in JavaScript. ``` var foo = { bar: "baz", qux: "quux", }; ``` Trailing commas simplify adding and removing items to objects and arrays, since only the lines you are modifying must be touched. Another argument in favor of trailing commas is that it improves the clarity of diffs when an item is added or removed from an object or array: Less clear: ``` var foo = { - bar: "baz", - qux: "quux" + bar: "baz" }; ``` More clear: ``` var foo = { bar: "baz", - qux: "quux", }; ``` Rule Details ------------ This rule enforces consistent use of trailing commas in object and array literals. Options ------- This rule has a string option or an object option: ``` { "comma-dangle": ["error", "never"], // or "comma-dangle": ["error", { "arrays": "never", "objects": "never", "imports": "never", "exports": "never", "functions": "never" }] } ``` * `"never"` (default) disallows trailing commas * `"always"` requires trailing commas * `"always-multiline"` requires trailing commas when the last element or property is in a *different* line than the closing `]` or `}` and disallows trailing commas when the last element or property is on the *same* line as the closing `]` or `}` * `"only-multiline"` allows (but does not require) trailing commas when the last element or property is in a *different* line than the closing `]` or `}` and disallows trailing commas when the last element or property is on the *same* line as the closing `]` or `}` You can also use an object option to configure this rule for each type of syntax. Each of the following options can be set to `"never"`, `"always"`, `"always-multiline"`, `"only-multiline"`, or `"ignore"`. The default for each option is `"never"` unless otherwise specified. * `arrays` is for array literals and array patterns of destructuring. (e.g. `let [a,] = [1,];`) * `objects` is for object literals and object patterns of destructuring. (e.g. `let {a,} = {a: 1};`) * `imports` is for import declarations of ES Modules. (e.g. `import {a,} from "foo";`) * `exports` is for export declarations of ES Modules. (e.g. `export {a,};`) * `functions` is for function declarations and function calls. (e.g. `(function(a,){ })(b,);`) + `functions` should only be enabled when linting ECMAScript 2017 or higher. ### never Examples of **incorrect** code for this rule with the default `"never"` option: ``` /\*eslint comma-dangle: ["error", "never"]\*/ var foo = { bar: "baz", qux: "quux", }; var arr = [1,2,]; foo({ bar: "baz", qux: "quux", }); ``` Examples of **correct** code for this rule with the default `"never"` option: ``` /\*eslint comma-dangle: ["error", "never"]\*/ var foo = { bar: "baz", qux: "quux" }; var arr = [1,2]; foo({ bar: "baz", qux: "quux" }); ``` ### always Examples of **incorrect** code for this rule with the `"always"` option: ``` /\*eslint comma-dangle: ["error", "always"]\*/ var foo = { bar: "baz", qux: "quux" }; var arr = [1,2]; foo({ bar: "baz", qux: "quux" }); ``` Examples of **correct** code for this rule with the `"always"` option: ``` /\*eslint comma-dangle: ["error", "always"]\*/ var foo = { bar: "baz", qux: "quux", }; var arr = [1,2,]; foo({ bar: "baz", qux: "quux", }); ``` ### always-multiline Examples of **incorrect** code for this rule with the `"always-multiline"` option: ``` /\*eslint comma-dangle: ["error", "always-multiline"]\*/ var foo = { bar: "baz", qux: "quux" }; var foo = { bar: "baz", qux: "quux", }; var arr = [1,2,]; var arr = [1, 2,]; var arr = [ 1, 2 ]; foo({ bar: "baz", qux: "quux" }); ``` Examples of **correct** code for this rule with the `"always-multiline"` option: ``` /\*eslint comma-dangle: ["error", "always-multiline"]\*/ var foo = { bar: "baz", qux: "quux", }; var foo = {bar: "baz", qux: "quux"}; var arr = [1,2]; var arr = [1, 2]; var arr = [ 1, 2, ]; foo({ bar: "baz", qux: "quux", }); ``` ### only-multiline Examples of **incorrect** code for this rule with the `"only-multiline"` option: ``` /\*eslint comma-dangle: ["error", "only-multiline"]\*/ var foo = { bar: "baz", qux: "quux", }; var arr = [1,2,]; var arr = [1, 2,]; ``` Examples of **correct** code for this rule with the `"only-multiline"` option: ``` /\*eslint comma-dangle: ["error", "only-multiline"]\*/ var foo = { bar: "baz", qux: "quux", }; var foo = { bar: "baz", qux: "quux" }; var foo = {bar: "baz", qux: "quux"}; var arr = [1,2]; var arr = [1, 2]; var arr = [ 1, 2, ]; var arr = [ 1, 2 ]; foo({ bar: "baz", qux: "quux", }); foo({ bar: "baz", qux: "quux" }); ``` ### functions Examples of **incorrect** code for this rule with the `{"functions": "never"}` option: ``` /\*eslint comma-dangle: ["error", {"functions": "never"}]\*/ function foo(a, b,) { } foo(a, b,); new foo(a, b,); ``` Examples of **correct** code for this rule with the `{"functions": "never"}` option: ``` /\*eslint comma-dangle: ["error", {"functions": "never"}]\*/ function foo(a, b) { } foo(a, b); new foo(a, b); ``` Examples of **incorrect** code for this rule with the `{"functions": "always"}` option: ``` /\*eslint comma-dangle: ["error", {"functions": "always"}]\*/ function foo(a, b) { } foo(a, b); new foo(a, b); ``` Examples of **correct** code for this rule with the `{"functions": "always"}` option: ``` /\*eslint comma-dangle: ["error", {"functions": "always"}]\*/ function foo(a, b,) { } foo(a, b,); new foo(a, b,); ``` When Not To Use It ------------------ You can turn this rule off if you are not concerned with dangling commas. Version ------- This rule was introduced in ESLint v0.16.0. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/comma-dangle.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/comma-dangle.js) eslint no-this-before-super no-this-before-super ==================== Disallow `this`/`super` before calling `super()` in constructors ✅ Recommended The `"extends": "eslint:recommended"` property in a [configuration file](no-this-before-super../user-guide/configuring/configuration-files#extending-configuration-files) enables this rule In the constructor of derived classes, if `this`/`super` are used before `super()` calls, it raises a reference error. This rule checks `this`/`super` keywords in constructors, then reports those that are before `super()`. Rule Details ------------ This rule is aimed to flag `this`/`super` keywords before `super()` callings. Examples -------- Examples of **incorrect** code for this rule: ``` /\*eslint no-this-before-super: "error"\*/ /\*eslint-env es6\*/ class A extends B { constructor() { this.a = 0; super(); } } class A extends B { constructor() { this.foo(); super(); } } class A extends B { constructor() { super.foo(); super(); } } class A extends B { constructor() { super(this.foo()); } } ``` Examples of **correct** code for this rule: ``` /\*eslint no-this-before-super: "error"\*/ /\*eslint-env es6\*/ class A { constructor() { this.a = 0; // OK, this class doesn't have an `extends` clause. } } class A extends B { constructor() { super(); this.a = 0; // OK, this is after `super()`. } } class A extends B { foo() { this.a = 0; // OK. this is not in a constructor. } } ``` When Not To Use It ------------------ If you don’t want to be notified about using `this`/`super` before `super()` in constructors, you can safely disable this rule. Version ------- This rule was introduced in ESLint v0.24.0. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/no-this-before-super.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/no-this-before-super.js)
programming_docs
eslint no-useless-constructor no-useless-constructor ====================== Disallow unnecessary constructors ES2015 provides a default class constructor if one is not specified. As such, it is unnecessary to provide an empty constructor or one that simply delegates into its parent class, as in the following examples: ``` class A { constructor () { } } class B extends A { constructor (value) { super(value); } } ``` Rule Details ------------ This rule flags class constructors that can be safely removed without changing how the class works. Examples -------- Examples of **incorrect** code for this rule: ``` /\*eslint no-useless-constructor: "error"\*/ /\*eslint-env es6\*/ class A { constructor () { } } class B extends A { constructor (...args) { super(...args); } } ``` Examples of **correct** code for this rule: ``` /\*eslint no-useless-constructor: "error"\*/ class A { } class A { constructor () { doSomething(); } } class B extends A { constructor() { super('foo'); } } class B extends A { constructor() { super(); doSomething(); } } ``` When Not To Use It ------------------ If you don’t want to be notified about unnecessary constructors, you can safely disable this rule. Version ------- This rule was introduced in ESLint v2.0.0-beta.1. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/no-useless-constructor.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/no-useless-constructor.js) eslint no-octal no-octal ======== Disallow octal literals ✅ Recommended The `"extends": "eslint:recommended"` property in a [configuration file](no-octal../user-guide/configuring/configuration-files#extending-configuration-files) enables this rule Octal literals are numerals that begin with a leading zero, such as: ``` var num = 071; // 57 ``` Because the leading zero which identifies an octal literal has been a source of confusion and error in JavaScript code, ECMAScript 5 deprecates the use of octal numeric literals. Rule Details ------------ The rule disallows octal literals. If ESLint parses code in strict mode, the parser (instead of this rule) reports the error. Examples of **incorrect** code for this rule: ``` /\*eslint no-octal: "error"\*/ var num = 071; var result = 5 + 07; ``` Examples of **correct** code for this rule: ``` /\*eslint no-octal: "error"\*/ var num = "071"; ``` Compatibility ------------- * **JSHint**: W115 Version ------- This rule was introduced in ESLint v0.0.6. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/no-octal.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/no-octal.js) eslint no-loop-func no-loop-func ============ Disallow function declarations that contain unsafe references inside loop statements Writing functions within loops tends to result in errors due to the way the function creates a closure around the loop. For example: ``` for (var i = 0; i < 10; i++) { funcs[i] = function() { return i; }; } ``` In this case, you would expect each function created within the loop to return a different number. In reality, each function returns 10, because that was the last value of `i` in the scope. `let` or `const` mitigate this problem. ``` /\*eslint-env es6\*/ for (let i = 0; i < 10; i++) { funcs[i] = function() { return i; }; } ``` In this case, each function created within the loop returns a different number as expected. Rule Details ------------ This error is raised to highlight a piece of code that may not work as you expect it to and could also indicate a misunderstanding of how the language works. Your code may run without any problems if you do not fix this error, but in some situations it could behave unexpectedly. This rule disallows any function within a loop that contains unsafe references (e.g. to modified variables from the outer scope). Examples of **incorrect** code for this rule: ``` /\*eslint no-loop-func: "error"\*/ /\*eslint-env es6\*/ for (var i=10; i; i--) { (function() { return i; })(); } while(i) { var a = function() { return i; }; a(); } do { function a() { return i; }; a(); } while (i); let foo = 0; for (let i = 0; i < 10; ++i) { //Bad, `foo` is not in the loop-block's scope and `foo` is modified in/after the loop setTimeout(() => console.log(foo)); foo += 1; } for (let i = 0; i < 10; ++i) { //Bad, `foo` is not in the loop-block's scope and `foo` is modified in/after the loop setTimeout(() => console.log(foo)); } foo = 100; ``` Examples of **correct** code for this rule: ``` /\*eslint no-loop-func: "error"\*/ /\*eslint-env es6\*/ var a = function() {}; for (var i=10; i; i--) { a(); } for (var i=10; i; i--) { var a = function() {}; // OK, no references to variables in the outer scopes. a(); } for (let i=10; i; i--) { var a = function() { return i; }; // OK, all references are referring to block scoped variables in the loop. a(); } var foo = 100; for (let i=10; i; i--) { var a = function() { return foo; }; // OK, all references are referring to never modified variables. a(); } //... no modifications of foo after this loop ... ``` Version ------- This rule was introduced in ESLint v0.0.9. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/no-loop-func.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/no-loop-func.js) eslint space-after-keywords space-after-keywords ==================== Enforces consistent spacing after keywords. (removed) This rule was **removed** in ESLint v2.0 and replaced by the [keyword-spacing](space-after-keywordskeyword-spacing) rule. (fixable) The `--fix` option on the [command line](space-after-keywords../user-guide/command-line-interface#--fix) automatically fixed problems reported by this rule. Some style guides will require or disallow spaces following the certain keywords. ``` if (condition) { doSomething(); } else { doSomethingElse(); } if(condition) { doSomething(); }else{ doSomethingElse(); } ``` Rule Details ------------ This rule will enforce consistency of spacing after the keywords `if`, `else`, `for`, `while`, `do`, `switch`, `try`, `catch`, `finally`, and `with`. This rule takes one argument. If it is `"always"` then the keywords must be followed by at least one space. If `"never"` then there should be no spaces following. The default is `"always"`. Examples of **incorrect** code for this rule: ``` /\*eslint space-after-keywords: "error"\*/ if(a) {} if (a) {} else{} do{} while (a); ``` ``` /\*eslint space-after-keywords: ["error", "never"]\*/ if (a) {} ``` Examples of **correct** code for this rule: ``` /\*eslint space-after-keywords: "error"\*/ if (a) {} if (a) {} else {} ``` ``` /\*eslint space-after-keywords: ["error", "never"]\*/ if(a) {} ``` Version ------- This rule was introduced in ESLint v0.6.0 and removed in v2.0.0-beta.3. eslint grouped-accessor-pairs grouped-accessor-pairs ====================== Require grouped accessor pairs in object literals and classes A getter and setter for the same property don’t necessarily have to be defined adjacent to each other. For example, the following statements would create the same object: ``` var o = { get a() { return this.val; }, set a(value) { this.val = value; }, b: 1 }; var o = { get a() { return this.val; }, b: 1, set a(value) { this.val = value; } }; ``` While it is allowed to define the pair for a getter or a setter anywhere in an object or class definition, it’s considered a best practice to group accessor functions for the same property. In other words, if a property has a getter and a setter, the setter should be defined right after the getter, or vice versa. Rule Details ------------ This rule requires grouped definitions of accessor functions for the same property in object literals, class declarations and class expressions. Optionally, this rule can also enforce consistent order (`getBeforeSet` or `setBeforeGet`). This rule does not enforce the existence of the pair for a getter or a setter. See [accessor-pairs](grouped-accessor-pairsaccessor-pairs) if you also want to enforce getter/setter pairs. Examples of **incorrect** code for this rule: ``` /\*eslint grouped-accessor-pairs: "error"\*/ var foo = { get a() { return this.val; }, b: 1, set a(value) { this.val = value; } }; var bar = { set b(value) { this.val = value; }, a: 1, get b() { return this.val; } } class Foo { set a(value) { this.val = value; } b(){} get a() { return this.val; } } const Bar = class { static get a() { return this.val; } b(){} static set a(value) { this.val = value; } } ``` Examples of **correct** code for this rule: ``` /\*eslint grouped-accessor-pairs: "error"\*/ var foo = { get a() { return this.val; }, set a(value) { this.val = value; }, b: 1 }; var bar = { set b(value) { this.val = value; }, get b() { return this.val; }, a: 1 } class Foo { set a(value) { this.val = value; } get a() { return this.val; } b(){} } const Bar = class { static get a() { return this.val; } static set a(value) { this.val = value; } b(){} } ``` Options ------- This rule has a string option: * `"anyOrder"` (default) does not enforce order. * `"getBeforeSet"` if a property has both getter and setter, requires the getter to be defined before the setter. * `"setBeforeGet"` if a property has both getter and setter, requires the setter to be defined before the getter. ### getBeforeSet Examples of **incorrect** code for this rule with the `"getBeforeSet"` option: ``` /\*eslint grouped-accessor-pairs: ["error", "getBeforeSet"]\*/ var foo = { set a(value) { this.val = value; }, get a() { return this.val; } }; class Foo { set a(value) { this.val = value; } get a() { return this.val; } } const Bar = class { static set a(value) { this.val = value; } static get a() { return this.val; } } ``` Examples of **correct** code for this rule with the `"getBeforeSet"` option: ``` /\*eslint grouped-accessor-pairs: ["error", "getBeforeSet"]\*/ var foo = { get a() { return this.val; }, set a(value) { this.val = value; } }; class Foo { get a() { return this.val; } set a(value) { this.val = value; } } const Bar = class { static get a() { return this.val; } static set a(value) { this.val = value; } } ``` ### setBeforeGet Examples of **incorrect** code for this rule with the `"setBeforeGet"` option: ``` /\*eslint grouped-accessor-pairs: ["error", "setBeforeGet"]\*/ var foo = { get a() { return this.val; }, set a(value) { this.val = value; } }; class Foo { get a() { return this.val; } set a(value) { this.val = value; } } const Bar = class { static get a() { return this.val; } static set a(value) { this.val = value; } } ``` Examples of **correct** code for this rule with the `"setBeforeGet"` option: ``` /\*eslint grouped-accessor-pairs: ["error", "setBeforeGet"]\*/ var foo = { set a(value) { this.val = value; }, get a() { return this.val; } }; class Foo { set a(value) { this.val = value; } get a() { return this.val; } } const Bar = class { static set a(value) { this.val = value; } static get a() { return this.val; } } ``` Known Limitations ----------------- Due to the limits of static analysis, this rule does not account for possible side effects and in certain cases might require or miss to require grouping or order for getters/setters that have a computed key, like in the following example: ``` /\*eslint grouped-accessor-pairs: "error"\*/ var a = 1; // false warning (false positive) var foo = { get [a++]() { return this.val; }, b: 1, set [a++](value) { this.val = value; } }; // missed warning (false negative) var bar = { get [++a]() { return this.val; }, b: 1, set [a](value) { this.val = value; } }; ``` Also, this rule does not report any warnings for properties that have duplicate getters or setters. See [no-dupe-keys](grouped-accessor-pairsno-dupe-keys) if you also want to disallow duplicate keys in object literals. See [no-dupe-class-members](grouped-accessor-pairsno-dupe-class-members) if you also want to disallow duplicate names in class definitions. Related Rules ------------- * <accessor-pairs> * <no-dupe-keys> * <no-dupe-class-members> Version ------- This rule was introduced in ESLint v6.7.0. Further Reading --------------- [setter - JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/set) [getter - JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get) [Classes - JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes) Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/grouped-accessor-pairs.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/grouped-accessor-pairs.js) eslint no-magic-numbers no-magic-numbers ================ Disallow magic numbers ‘Magic numbers’ are numbers that occur multiple times in code without an explicit meaning. They should preferably be replaced by named constants. ``` var now = Date.now(), inOneHour = now + (60 \* 60 \* 1000); ``` Rule Details ------------ The `no-magic-numbers` rule aims to make code more readable and refactoring easier by ensuring that special numbers are declared as constants to make their meaning explicit. Examples of **incorrect** code for this rule: ``` /\*eslint no-magic-numbers: "error"\*/ var dutyFreePrice = 100, finalPrice = dutyFreePrice + (dutyFreePrice \* 0.25); ``` ``` /\*eslint no-magic-numbers: "error"\*/ var data = ['foo', 'bar', 'baz']; var dataLast = data[2]; ``` ``` /\*eslint no-magic-numbers: "error"\*/ var SECONDS; SECONDS = 60; ``` Examples of **correct** code for this rule: ``` /\*eslint no-magic-numbers: "error"\*/ var TAX = 0.25; var dutyFreePrice = 100, finalPrice = dutyFreePrice + (dutyFreePrice \* TAX); ``` Options ------- ### ignore An array of numbers to ignore. It’s set to `[]` by default. If provided, it must be an `Array`. The array can contain values of `number` and `string` types. If it’s a string, the text must be parsed as `bigint` literal (e.g., `"100n"`). Examples of **correct** code for the sample `{ "ignore": [1] }` option: ``` /\*eslint no-magic-numbers: ["error", { "ignore": [1] }]\*/ var data = ['foo', 'bar', 'baz']; var dataLast = data.length && data[data.length - 1]; ``` Examples of **correct** code for the sample `{ "ignore": ["1n"] }` option: ``` /\*eslint no-magic-numbers: ["error", { "ignore": ["1n"] }]\*/ foo(1n); ``` ### ignoreArrayIndexes A boolean to specify if numbers used in the context of array indexes (e.g., `data[2]`) are considered okay. `false` by default. This option allows only valid array indexes: numbers that will be coerced to one of `"0"`, `"1"`, `"2"` … `"4294967294"`. Arrays are objects, so they can have property names such as `"-1"` or `"2.5"`. However, those are just “normal” object properties that don’t represent array elements. They don’t influence the array’s `length`, and they are ignored by array methods like `.map` or `.forEach`. Additionally, since the maximum [array length](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/length) is 232 - 1, all values above 232 - 2 also represent just normal property names and are thus not considered to be array indexes. Examples of **correct** code for the `{ "ignoreArrayIndexes": true }` option: ``` /\*eslint no-magic-numbers: ["error", { "ignoreArrayIndexes": true }]\*/ var item = data[2]; data[100] = a; f(data[0]); a = data[-0]; // same as data[0], -0 will be coerced to "0" a = data[0xAB]; a = data[5.6e1]; a = data[10n]; // same as data[10], 10n will be coerced to "10" a = data[4294967294]; // max array index ``` Examples of **incorrect** code for the `{ "ignoreArrayIndexes": true }` option: ``` /\*eslint no-magic-numbers: ["error", { "ignoreArrayIndexes": true }]\*/ f(2); // not used as array index a = data[-1]; a = data[2.5]; a = data[5.67e1]; a = data[-10n]; a = data[4294967295]; // above the max array index a = data[1e500]; // same as data["Infinity"] ``` ### ignoreDefaultValues A boolean to specify if numbers used in default value assignments are considered okay. `false` by default. Examples of **correct** code for the `{ "ignoreDefaultValues": true }` option: ``` /\*eslint no-magic-numbers: ["error", { "ignoreDefaultValues": true }]\*/ const { tax = 0.25 } = accountancy; function mapParallel(concurrency = 3) { /\*\*\*/ } ``` ``` /\*eslint no-magic-numbers: ["error", { "ignoreDefaultValues": true }]\*/ let head; [head = 100] = [] ``` ### ignoreClassFieldInitialValues A boolean to specify if numbers used as initial values of class fields are considered okay. `false` by default. Examples of **correct** code for the `{ "ignoreClassFieldInitialValues": true }` option: ``` /\*eslint no-magic-numbers: ["error", { "ignoreClassFieldInitialValues": true }]\*/ class C { foo = 2; bar = -3; #baz = 4; static qux = 5; } ``` Examples of **incorrect** code for the `{ "ignoreClassFieldInitialValues": true }` option: ``` /\*eslint no-magic-numbers: ["error", { "ignoreClassFieldInitialValues": true }]\*/ class C { foo = 2 + 3; } class D { 2; } ``` ### enforceConst A boolean to specify if we should check for the const keyword in variable declaration of numbers. `false` by default. Examples of **incorrect** code for the `{ "enforceConst": true }` option: ``` /\*eslint no-magic-numbers: ["error", { "enforceConst": true }]\*/ var TAX = 0.25; var dutyFreePrice = 100, finalPrice = dutyFreePrice + (dutyFreePrice \* TAX); ``` ### detectObjects A boolean to specify if we should detect numbers when setting object properties for example. `false` by default. Examples of **incorrect** code for the `{ "detectObjects": true }` option: ``` /\*eslint no-magic-numbers: ["error", { "detectObjects": true }]\*/ var magic = { tax: 0.25 }; var dutyFreePrice = 100, finalPrice = dutyFreePrice + (dutyFreePrice \* magic.tax); ``` Examples of **correct** code for the `{ "detectObjects": true }` option: ``` /\*eslint no-magic-numbers: ["error", { "detectObjects": true }]\*/ var TAX = 0.25; var magic = { tax: TAX }; var dutyFreePrice = 100, finalPrice = dutyFreePrice + (dutyFreePrice \* magic.tax); ``` Version ------- This rule was introduced in ESLint v1.7.0. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/no-magic-numbers.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/no-magic-numbers.js)
programming_docs
eslint prefer-object-has-own prefer-object-has-own ===================== Disallow use of `Object.prototype.hasOwnProperty.call()` and prefer use of `Object.hasOwn()` 🔧 Fixable Some problems reported by this rule are automatically fixable by the `--fix` [command line](prefer-object-has-own../user-guide/command-line-interface#--fix) option It is very common to write code like: ``` if (Object.prototype.hasOwnProperty.call(object, "foo")) { console.log("has property foo"); } ``` This is a common practice because methods on `Object.prototype` can sometimes be unavailable or redefined (see the [no-prototype-builtins](prefer-object-has-ownno-prototype-builtins) rule). Introduced in ES2022, `Object.hasOwn()` is a shorter alternative to `Object.prototype.hasOwnProperty.call()`: ``` if (Object.hasOwn(object, "foo")) { console.log("has property foo") } ``` Rule Details ------------ Examples of **incorrect** code for this rule: ``` /\*eslint prefer-object-has-own: "error"\*/ Object.prototype.hasOwnProperty.call(obj, "a"); Object.hasOwnProperty.call(obj, "a"); ({}).hasOwnProperty.call(obj, "a"); const hasProperty = Object.prototype.hasOwnProperty.call(object, property); ``` Examples of **correct** code for this rule: ``` /\*eslint prefer-object-has-own: "error"\*/ Object.hasOwn(obj, "a"); const hasProperty = Object.hasOwn(object, property); ``` When Not To Use It ------------------ This rule should not be used unless ES2022 is supported in your codebase. Version ------- This rule was introduced in ESLint v8.5.0. Further Reading --------------- [Object.hasOwn() - JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwn) Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/prefer-object-has-own.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/prefer-object-has-own.js) eslint block-scoped-var block-scoped-var ================ Enforce the use of variables within the scope they are defined The `block-scoped-var` rule generates warnings when variables are used outside of the block in which they were defined. This emulates C-style block scope. Rule Details ------------ This rule aims to reduce the usage of variables outside of their binding context and emulate traditional block scope from other languages. This is to help newcomers to the language avoid difficult bugs with variable hoisting. Examples of **incorrect** code for this rule: ``` /\*eslint block-scoped-var: "error"\*/ function doIf() { if (true) { var build = true; } console.log(build); } function doIfElse() { if (true) { var build = true; } else { var build = false; } } function doTryCatch() { try { var build = 1; } catch (e) { var f = build; } } function doFor() { for (var x = 1; x < 10; x++) { var y = f(x); } console.log(y); } class C { static { if (something) { var build = true; } build = false; } } ``` Examples of **correct** code for this rule: ``` /\*eslint block-scoped-var: "error"\*/ function doIf() { var build; if (true) { build = true; } console.log(build); } function doIfElse() { var build; if (true) { build = true; } else { build = false; } } function doTryCatch() { var build; var f; try { build = 1; } catch (e) { f = build; } } function doFor() { for (var x = 1; x < 10; x++) { var y = f(x); console.log(y); } } class C { static { var build = false; if (something) { build = true; } } } ``` Version ------- This rule was introduced in ESLint v0.1.0. Further Reading --------------- [JavaScript Scoping and Hoisting](https://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html) [var - JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var#var_hoisting) Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/block-scoped-var.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/block-scoped-var.js) eslint nonblock-statement-body-position nonblock-statement-body-position ================================ Enforce the location of single-line statements 🔧 Fixable Some problems reported by this rule are automatically fixable by the `--fix` [command line](nonblock-statement-body-position../user-guide/command-line-interface#--fix) option When writing `if`, `else`, `while`, `do-while`, and `for` statements, the body can be a single statement instead of a block. It can be useful to enforce a consistent location for these single statements. For example, some developers avoid writing code like this: ``` if (foo) bar(); ``` If another developer attempts to add `baz();` to the `if` statement, they might mistakenly change the code to ``` if (foo) bar(); baz(); // this line is not in the `if` statement! ``` To avoid this issue, one might require all single-line `if` statements to appear directly after the conditional, without a linebreak: ``` if (foo) bar(); ``` Rule Details ------------ This rule aims to enforce a consistent location for single-line statements. Note that this rule does not enforce the usage of single-line statements in general. If you would like to disallow single-line statements, use the [`curly`](nonblock-statement-body-positioncurly) rule instead. ### Options This rule accepts a string option: * `"beside"` (default) disallows a newline before a single-line statement. * `"below"` requires a newline before a single-line statement. * `"any"` does not enforce the position of a single-line statement. Additionally, the rule accepts an optional object option with an `"overrides"` key. This can be used to specify a location for particular statements that override the default. For example: * `"beside", { "overrides": { "while": "below" } }` requires all single-line statements to appear on the same line as their parent, unless the parent is a `while` statement, in which case the single-line statement must not be on the same line. * `"below", { "overrides": { "do": "any" } }` disallows all single-line statements from appearing on the same line as their parent, unless the parent is a `do-while` statement, in which case the position of the single-line statement is not enforced. Examples of **incorrect** code for this rule with the default `"beside"` option: ``` /\* eslint nonblock-statement-body-position: ["error", "beside"] \*/ if (foo) bar(); else baz(); while (foo) bar(); for (let i = 1; i < foo; i++) bar(); do bar(); while (foo) ``` Examples of **correct** code for this rule with the default `"beside"` option: ``` /\* eslint nonblock-statement-body-position: ["error", "beside"] \*/ if (foo) bar(); else baz(); while (foo) bar(); for (let i = 1; i < foo; i++) bar(); do bar(); while (foo) if (foo) { // block statements are always allowed with this rule bar(); } else { baz(); } ``` Examples of **incorrect** code for this rule with the `"below"` option: ``` /\* eslint nonblock-statement-body-position: ["error", "below"] \*/ if (foo) bar(); else baz(); while (foo) bar(); for (let i = 1; i < foo; i++) bar(); do bar(); while (foo) ``` Examples of **correct** code for this rule with the `"below"` option: ``` /\* eslint nonblock-statement-body-position: ["error", "below"] \*/ if (foo) bar(); else baz(); while (foo) bar(); for (let i = 1; i < foo; i++) bar(); do bar(); while (foo) if (foo) { // Although the second `if` statement is on the same line as the `else`, this is a very common // pattern, so it's not checked by this rule. } else if (bar) { } ``` Examples of **incorrect** code for this rule with the `"beside", { "overrides": { "while": "below" } }` rule: ``` /\* eslint nonblock-statement-body-position: ["error", "beside", { "overrides": { "while": "below" } }] \*/ if (foo) bar(); while (foo) bar(); ``` Examples of **correct** code for this rule with the `"beside", { "overrides": { "while": "below" } }` rule: ``` /\* eslint nonblock-statement-body-position: ["error", "beside", { "overrides": { "while": "below" } }] \*/ if (foo) bar(); while (foo) bar(); ``` When Not To Use It ------------------ If you’re not concerned about consistent locations of single-line statements, you should not turn on this rule. You can also disable this rule if you’re using the `"all"` option for the [`curly`](nonblock-statement-body-positioncurly) rule, because this will disallow single-line statements entirely. Version ------- This rule was introduced in ESLint v3.17.0. Further Reading --------------- [JSCS](https://jscs-dev.github.io/rule/requireNewlineBeforeSingleStatementsInIf) Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/nonblock-statement-body-position.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/nonblock-statement-body-position.js) eslint dot-notation dot-notation ============ Enforce dot notation whenever possible 🔧 Fixable Some problems reported by this rule are automatically fixable by the `--fix` [command line](dot-notation../user-guide/command-line-interface#--fix) option In JavaScript, one can access properties using the dot notation (`foo.bar`) or square-bracket notation (`foo["bar"]`). However, the dot notation is often preferred because it is easier to read, less verbose, and works better with aggressive JavaScript minimizers. ``` foo["bar"]; ``` Rule Details ------------ This rule is aimed at maintaining code consistency and improving code readability by encouraging use of the dot notation style whenever possible. As such, it will warn when it encounters an unnecessary use of square-bracket notation. Examples of **incorrect** code for this rule: ``` /\*eslint dot-notation: "error"\*/ var x = foo["bar"]; ``` Examples of **correct** code for this rule: ``` /\*eslint dot-notation: "error"\*/ var x = foo.bar; var x = foo[bar]; // Property name is a variable, square-bracket notation required ``` Options ------- This rule accepts a single options argument: * Set the `allowKeywords` option to `false` (default is `true`) to follow ECMAScript version 3 compatible style, avoiding dot notation for reserved word properties. * Set the `allowPattern` option to a regular expression string to allow bracket notation for property names that match a pattern (by default, no pattern is tested). ### allowKeywords Examples of **correct** code for the `{ "allowKeywords": false }` option: ``` /\*eslint dot-notation: ["error", { "allowKeywords": false }]\*/ var foo = { "class": "CS 101" } var x = foo["class"]; // Property name is a reserved word, square-bracket notation required ``` Examples of additional **correct** code for the `{ "allowKeywords": false }` option: ``` /\*eslint dot-notation: ["error", { "allowKeywords": false }]\*/ class C { #in; foo() { this.#in; // Dot notation is required for private identifiers } } ``` ### allowPattern For example, when preparing data to be sent to an external API, it is often required to use property names that include underscores. If the `camelcase` rule is in effect, these [snake case](https://en.wikipedia.org/wiki/Snake_case) properties would not be allowed. By providing an `allowPattern` to the `dot-notation` rule, these snake case properties can be accessed with bracket notation. Examples of **correct** code for the sample `{ "allowPattern": "^[a-z]+(_[a-z]+)+$" }` option: ``` /\*eslint camelcase: "error"\*/ /\*eslint dot-notation: ["error", { "allowPattern": "^[a-z]+(\_[a-z]+)+$" }]\*/ var data = {}; data.foo_bar = 42; var data = {}; data["fooBar"] = 42; var data = {}; data["foo\_bar"] = 42; // no warning ``` Version ------- This rule was introduced in ESLint v0.0.7. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/dot-notation.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/dot-notation.js) eslint prefer-numeric-literals prefer-numeric-literals ======================= Disallow `parseInt()` and `Number.parseInt()` in favor of binary, octal, and hexadecimal literals 🔧 Fixable Some problems reported by this rule are automatically fixable by the `--fix` [command line](prefer-numeric-literals../user-guide/command-line-interface#--fix) option The `parseInt()` and `Number.parseInt()` functions can be used to turn binary, octal, and hexadecimal strings into integers. As binary, octal, and hexadecimal literals are supported in ES6, this rule encourages use of those numeric literals instead of `parseInt()` or `Number.parseInt()`. ``` 0b111110111 === 503; 0o767 === 503; ``` Rule Details ------------ This rule disallows calls to `parseInt()` or `Number.parseInt()` if called with two arguments: a string; and a radix option of 2 (binary), 8 (octal), or 16 (hexadecimal). Examples of **incorrect** code for this rule: ``` /\*eslint prefer-numeric-literals: "error"\*/ parseInt("111110111", 2) === 503; parseInt(`111110111`, 2) === 503; parseInt("767", 8) === 503; parseInt("1F7", 16) === 503; Number.parseInt("111110111", 2) === 503; Number.parseInt("767", 8) === 503; Number.parseInt("1F7", 16) === 503; ``` Examples of **correct** code for this rule: ``` /\*eslint prefer-numeric-literals: "error"\*/ /\*eslint-env es6\*/ parseInt(1); parseInt(1, 3); Number.parseInt(1); Number.parseInt(1, 3); 0b111110111 === 503; 0o767 === 503; 0x1F7 === 503; a[parseInt](1,2); parseInt(foo); parseInt(foo, 2); Number.parseInt(foo); Number.parseInt(foo, 2); ``` When Not To Use It ------------------ If you want to allow use of `parseInt()` or `Number.parseInt()` for binary, octal, or hexadecimal integers, or if you are not using ES6 (because binary and octal literals are not supported in ES5 and below), you may wish to disable this rule. Compatibility ------------- * **JSCS**: [requireNumericLiterals](https://jscs-dev.github.io/rule/requireNumericLiterals) Version ------- This rule was introduced in ESLint v3.5.0. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/prefer-numeric-literals.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/prefer-numeric-literals.js) eslint no-empty-character-class no-empty-character-class ======================== Disallow empty character classes in regular expressions ✅ Recommended The `"extends": "eslint:recommended"` property in a [configuration file](no-empty-character-class../user-guide/configuring/configuration-files#extending-configuration-files) enables this rule Because empty character classes in regular expressions do not match anything, they might be typing mistakes. ``` var foo = /^abc[]/; ``` Rule Details ------------ This rule disallows empty character classes in regular expressions. Examples of **incorrect** code for this rule: ``` /\*eslint no-empty-character-class: "error"\*/ /^abc[]/.test("abcdefg"); // false "abcdefg".match(/^abc[]/); // null ``` Examples of **correct** code for this rule: ``` /\*eslint no-empty-character-class: "error"\*/ /^abc/.test("abcdefg"); // true "abcdefg".match(/^abc/); // ["abc"] /^abc[a-z]/.test("abcdefg"); // true "abcdefg".match(/^abc[a-z]/); // ["abcd"] ``` Known Limitations ----------------- This rule does not report empty character classes in the string argument of calls to the `RegExp` constructor. Example of a *false negative* when this rule reports correct code: ``` /\*eslint no-empty-character-class: "error"\*/ var abcNeverMatches = new RegExp("^abc[]"); ``` Version ------- This rule was introduced in ESLint v0.22.0. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/no-empty-character-class.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/no-empty-character-class.js) eslint no-implicit-coercion no-implicit-coercion ==================== Disallow shorthand type conversions 🔧 Fixable Some problems reported by this rule are automatically fixable by the `--fix` [command line](no-implicit-coercion../user-guide/command-line-interface#--fix) option In JavaScript, there are a lot of different ways to convert value types. Some of them might be hard to read and understand. Such as: ``` var b = !!foo; var b = ~foo.indexOf("."); var n = +foo; var n = 1 \* foo; var s = "" + foo; foo += ``; ``` Those can be replaced with the following code: ``` var b = Boolean(foo); var b = foo.indexOf(".") !== -1; var n = Number(foo); var n = Number(foo); var s = String(foo); foo = String(foo); ``` Rule Details ------------ This rule is aimed to flag shorter notations for the type conversion, then suggest a more self-explanatory notation. Options ------- This rule has three main options and one override option to allow some coercions as required. * `"boolean"` (`true` by default) - When this is `true`, this rule warns shorter type conversions for `boolean` type. * `"number"` (`true` by default) - When this is `true`, this rule warns shorter type conversions for `number` type. * `"string"` (`true` by default) - When this is `true`, this rule warns shorter type conversions for `string` type. * `"disallowTemplateShorthand"` (`false` by default) - When this is `true`, this rule warns `string` type conversions using `${expression}` form. * `"allow"` (`empty` by default) - Each entry in this array can be one of `~`, `!!`, `+` or `*` that are to be allowed. Note that operator `+` in `allow` list would allow `+foo` (number coercion) as well as `"" + foo` (string coercion). ### boolean Examples of **incorrect** code for the default `{ "boolean": true }` option: ``` /\*eslint no-implicit-coercion: "error"\*/ var b = !!foo; var b = ~foo.indexOf("."); // bitwise not is incorrect only with `indexOf`/`lastIndexOf` method calling. ``` Examples of **correct** code for the default `{ "boolean": true }` option: ``` /\*eslint no-implicit-coercion: "error"\*/ var b = Boolean(foo); var b = foo.indexOf(".") !== -1; var n = ~foo; // This is a just bitwise not. ``` ### number Examples of **incorrect** code for the default `{ "number": true }` option: ``` /\*eslint no-implicit-coercion: "error"\*/ var n = +foo; var n = 1 \* foo; ``` Examples of **correct** code for the default `{ "number": true }` option: ``` /\*eslint no-implicit-coercion: "error"\*/ var n = Number(foo); var n = parseFloat(foo); var n = parseInt(foo, 10); var n = foo \* 1/4; // `\* 1` is allowed when followed by the `/` operator ``` ### string Examples of **incorrect** code for the default `{ "string": true }` option: ``` /\*eslint no-implicit-coercion: "error"\*/ var s = "" + foo; var s = `` + foo; foo += ""; foo += ``; ``` Examples of **correct** code for the default `{ "string": true }` option: ``` /\*eslint no-implicit-coercion: "error"\*/ var s = String(foo); foo = String(foo); ``` ### disallowTemplateShorthand This option is **not** affected by the `string` option. Examples of **incorrect** code for the `{ "disallowTemplateShorthand": true }` option: ``` /\*eslint no-implicit-coercion: ["error", { "disallowTemplateShorthand": true }]\*/ var s = `${foo}`; ``` Examples of **correct** code for the `{ "disallowTemplateShorthand": true }` option: ``` /\*eslint no-implicit-coercion: ["error", { "disallowTemplateShorthand": true }]\*/ var s = String(foo); var s = `a${foo}`; var s = `${foo}b`; var s = `${foo}${bar}`; var s = tag`${foo}`; ``` Examples of **correct** code for the default `{ "disallowTemplateShorthand": false }` option: ``` /\*eslint no-implicit-coercion: ["error", { "disallowTemplateShorthand": false }]\*/ var s = `${foo}`; ``` ### allow Using `allow` list, we can override and allow specific operators. Examples of **correct** code for the sample `{ "allow": ["!!", "~"] }` option: ``` /\*eslint no-implicit-coercion: [2, { "allow": ["!!", "~"] } ]\*/ var b = !!foo; var b = ~foo.indexOf("."); ``` When Not To Use It ------------------ If you don’t want to be notified about shorter notations for the type conversion, you can safely disable this rule. Version ------- This rule was introduced in ESLint v1.0.0-rc-2. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/no-implicit-coercion.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/no-implicit-coercion.js)
programming_docs
eslint no-invalid-regexp no-invalid-regexp ================= Disallow invalid regular expression strings in `RegExp` constructors ✅ Recommended The `"extends": "eslint:recommended"` property in a [configuration file](no-invalid-regexp../user-guide/configuring/configuration-files#extending-configuration-files) enables this rule An invalid pattern in a regular expression literal is a `SyntaxError` when the code is parsed, but an invalid string in `RegExp` constructors throws a `SyntaxError` only when the code is executed. Rule Details ------------ This rule disallows invalid regular expression strings in `RegExp` constructors. Examples of **incorrect** code for this rule: ``` /\*eslint no-invalid-regexp: "error"\*/ RegExp('[') RegExp('.', 'z') new RegExp('\\') ``` Examples of **correct** code for this rule: ``` /\*eslint no-invalid-regexp: "error"\*/ RegExp('.') new RegExp this.RegExp('[') ``` Please note that this rule validates regular expressions per the latest ECMAScript specification, regardless of your parser settings. If you want to allow additional constructor flags for any reason, you can specify them using the `allowConstructorFlags` option. These flags will then be ignored by the rule. Options ------- This rule has an object option for exceptions: * `"allowConstructorFlags"` is an array of flags ### allowConstructorFlags Examples of **correct** code for this rule with the `{ "allowConstructorFlags": ["a", "z"] }` option: ``` /\*eslint no-invalid-regexp: ["error", { "allowConstructorFlags": ["a", "z"] }]\*/ new RegExp('.', 'a') new RegExp('.', 'az') ``` Version ------- This rule was introduced in ESLint v0.1.4. Further Reading --------------- [Annotated ES5](https://es5.github.io/#x7.8.5) Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/no-invalid-regexp.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/no-invalid-regexp.js) eslint newline-after-var newline-after-var ================= Require or disallow an empty line after variable declarations 🔧 Fixable Some problems reported by this rule are automatically fixable by the `--fix` [command line](newline-after-var../user-guide/command-line-interface#--fix) option This rule was **deprecated** in ESLint v4.0.0 and replaced by the [padding-line-between-statements](newline-after-varpadding-line-between-statements) rule. As of today there is no consistency in separating variable declarations from the rest of the code. Some developers leave an empty line between var statements and the rest of the code like: ``` var foo; // do something with foo ``` Whereas others don’t leave any empty newlines at all. ``` var foo; // do something with foo ``` The problem is when these developers work together in a project. This rule enforces a coding style where empty newlines are allowed or disallowed after `var`, `let`, or `const` statements. It helps the code to look consistent across the entire project. Rule Details ------------ This rule enforces a coding style where empty lines are required or disallowed after `var`, `let`, or `const` statements to achieve a consistent coding style across the project. Options ------- This rule has a string option: * `"always"` (default) requires an empty line after `var`, `let`, or `const` Comments on a line directly after var statements are treated like additional var statements. * `"never"` disallows empty lines after `var`, `let`, or `const` ### always Examples of **incorrect** code for this rule with the default `"always"` option: ``` /\*eslint newline-after-var: ["error", "always"]\*/ /\*eslint-env es6\*/ var greet = "hello,", name = "world"; console.log(greet, name); let greet = "hello,", name = "world"; console.log(greet, name); var greet = "hello,"; const NAME = "world"; console.log(greet, NAME); var greet = "hello,"; var name = "world"; // var name = require("world"); console.log(greet, name); ``` Examples of **correct** code for this rule with the default `"always"` option: ``` /\*eslint newline-after-var: ["error", "always"]\*/ /\*eslint-env es6\*/ var greet = "hello,", name = "world"; console.log(greet, name); let greet = "hello,", name = "world"; console.log(greet, name); var greet = "hello,"; const NAME = "world"; console.log(greet, NAME); var greet = "hello,"; var name = "world"; // var name = require("world"); console.log(greet, name); ``` ### never Examples of **incorrect** code for this rule with the `"never"` option: ``` /\*eslint newline-after-var: ["error", "never"]\*/ /\*eslint-env es6\*/ var greet = "hello,", name = "world"; console.log(greet, name); let greet = "hello,", name = "world"; console.log(greet, name); var greet = "hello,"; const NAME = "world"; console.log(greet, NAME); var greet = "hello,"; var name = "world"; // var name = require("world"); console.log(greet, name); ``` Examples of **correct** code for this rule with the `"never"` option: ``` /\*eslint newline-after-var: ["error", "never"]\*/ /\*eslint-env es6\*/ var greet = "hello,", name = "world"; console.log(greet, name); let greet = "hello,", name = "world"; console.log(greet, name); var greet = "hello,"; const NAME = "world"; console.log(greet, NAME); var greet = "hello,"; var name = "world"; // var name = require("world"); console.log(greet, name); ``` Version ------- This rule was introduced in ESLint v0.18.0. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/newline-after-var.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/newline-after-var.js) eslint padded-blocks padded-blocks ============= Require or disallow padding within blocks 🔧 Fixable Some problems reported by this rule are automatically fixable by the `--fix` [command line](padded-blocks../user-guide/command-line-interface#--fix) option Some style guides require block statements to start and end with blank lines. The goal is to improve readability by visually separating the block content and the surrounding code. ``` if (a) { b(); } ``` Since it’s good to have a consistent code style, you should either always write padded blocks or never do it. Rule Details ------------ This rule enforces consistent empty line padding within blocks. Options ------- This rule has two options, the first one can be a string option or an object option. The second one is an object option, it can allow exceptions. ### First option String option: * `"always"` (default) requires empty lines at the beginning and ending of block statements, function bodies, class static blocks, classes, and `switch` statements. * `"never"` disallows empty lines at the beginning and ending of block statements, function bodies, class static blocks, classes, and `switch` statements. Object option: * `"blocks"` require or disallow padding within block statements, function bodies, and class static blocks * `"classes"` require or disallow padding within classes * `"switches"` require or disallow padding within `switch` statements ### Second option * `"allowSingleLineBlocks": true` allows single-line blocks ### always Examples of **incorrect** code for this rule with the default `"always"` option: ``` /\*eslint padded-blocks: ["error", "always"]\*/ if (a) { b(); } if (a) { b(); } if (a) { b(); } if (a) { b(); } if (a) { // comment b(); } class C { static { a(); } } ``` Examples of **correct** code for this rule with the default `"always"` option: ``` /\*eslint padded-blocks: ["error", "always"]\*/ if (a) { b(); } if (a) { b(); } if (a) { // comment b(); } class C { static { a(); } } ``` ### never Examples of **incorrect** code for this rule with the `"never"` option: ``` /\*eslint padded-blocks: ["error", "never"]\*/ if (a) { b(); } if (a) { b(); } if (a) { b(); } if (a) { b(); } class C { static { a(); } } ``` Examples of **correct** code for this rule with the `"never"` option: ``` /\*eslint padded-blocks: ["error", "never"]\*/ if (a) { b(); } if (a) { b(); } class C { static { a(); } } ``` ### blocks Examples of **incorrect** code for this rule with the `{ "blocks": "always" }` option: ``` /\*eslint padded-blocks: ["error", { "blocks": "always" }]\*/ if (a) { b(); } if (a) { b(); } if (a) { b(); } if (a) { b(); } if (a) { b(); } if (a) { // comment b(); } class C { static { a(); } } ``` Examples of **correct** code for this rule with the `{ "blocks": "always" }` option: ``` /\*eslint padded-blocks: ["error", { "blocks": "always" }]\*/ if (a) { b(); } if (a) { b(); } if (a) { // comment b(); } class C { static { a(); } } class D { static { a(); } } ``` Examples of **incorrect** code for this rule with the `{ "blocks": "never" }` option: ``` /\*eslint padded-blocks: ["error", { "blocks": "never" }]\*/ if (a) { b(); } if (a) { b(); } if (a) { b(); } if (a) { b(); } class C { static { a(); } } ``` Examples of **correct** code for this rule with the `{ "blocks": "never" }` option: ``` /\*eslint padded-blocks: ["error", { "blocks": "never" }]\*/ if (a) { b(); } if (a) { b(); } class C { static { a(); } } class D { static { a(); } } ``` ### classes Examples of **incorrect** code for this rule with the `{ "classes": "always" }` option: ``` /\*eslint padded-blocks: ["error", { "classes": "always" }]\*/ class A { constructor(){ } } ``` Examples of **correct** code for this rule with the `{ "classes": "always" }` option: ``` /\*eslint padded-blocks: ["error", { "classes": "always" }]\*/ class A { constructor(){ } } ``` Examples of **incorrect** code for this rule with the `{ "classes": "never" }` option: ``` /\*eslint padded-blocks: ["error", { "classes": "never" }]\*/ class A { constructor(){ } } ``` Examples of **correct** code for this rule with the `{ "classes": "never" }` option: ``` /\*eslint padded-blocks: ["error", { "classes": "never" }]\*/ class A { constructor(){ } } ``` ### switches Examples of **incorrect** code for this rule with the `{ "switches": "always" }` option: ``` /\*eslint padded-blocks: ["error", { "switches": "always" }]\*/ switch (a) { case 0: foo(); } ``` Examples of **correct** code for this rule with the `{ "switches": "always" }` option: ``` /\*eslint padded-blocks: ["error", { "switches": "always" }]\*/ switch (a) { case 0: foo(); } if (a) { b(); } ``` Examples of **incorrect** code for this rule with the `{ "switches": "never" }` option: ``` /\*eslint padded-blocks: ["error", { "switches": "never" }]\*/ switch (a) { case 0: foo(); } ``` Examples of **correct** code for this rule with the `{ "switches": "never" }` option: ``` /\*eslint padded-blocks: ["error", { "switches": "never" }]\*/ switch (a) { case 0: foo(); } if (a) { b(); } ``` ### always + allowSingleLineBlocks Examples of **incorrect** code for this rule with the `"always", {"allowSingleLineBlocks": true}` options: ``` /\*eslint padded-blocks: ["error", "always", { allowSingleLineBlocks: true }]\*/ if (a) { b(); } if (a) { b(); } if (a) { b(); } ``` Examples of **correct** code for this rule with the `"always", {"allowSingleLineBlocks": true}` options: ``` /\*eslint padded-blocks: ["error", "always", { allowSingleLineBlocks: true }]\*/ if (a) { b(); } if (a) { b(); } ``` When Not To Use It ------------------ You can turn this rule off if you are not concerned with the consistency of padding within blocks. Related Rules ------------- * <lines-between-class-members> * <padding-line-between-statements> Version ------- This rule was introduced in ESLint v0.9.0. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/padded-blocks.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/padded-blocks.js) eslint require-unicode-regexp require-unicode-regexp ====================== Enforce the use of `u` flag on RegExp RegExp `u` flag has two effects: 1. **Make the regular expression handling UTF-16 surrogate pairs correctly.** Especially, character range syntax gets the correct behavior. ``` /^[👍]$/.test("👍") //→ false /^[👍]$/u.test("👍") //→ true ``` 2. **Make the regular expression throwing syntax errors early as disabling [Annex B extensions](https://www.ecma-international.org/ecma-262/6.0/#sec-regular-expressions-patterns).** Because of historical reason, JavaScript regular expressions are tolerant of syntax errors. For example, `/\w{1, 2/` is a syntax error, but JavaScript doesn’t throw the error. It matches strings such as `"a{1, 2"` instead. Such a recovering logic is defined in Annex B. The `u` flag disables the recovering logic Annex B defined. As a result, you can find errors early. This is similar to [the strict mode](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode). Therefore, the `u` flag lets us work better with regular expressions. Rule Details ------------ This rule aims to enforce the use of `u` flag on regular expressions. Examples of **incorrect** code for this rule: ``` /\*eslint require-unicode-regexp: error \*/ const a = /aaa/ const b = /bbb/gi const c = new RegExp("ccc") const d = new RegExp("ddd", "gi") ``` Examples of **correct** code for this rule: ``` /\*eslint require-unicode-regexp: error \*/ const a = /aaa/u const b = /bbb/giu const c = new RegExp("ccc", "u") const d = new RegExp("ddd", "giu") // This rule ignores RegExp calls if the flags could not be evaluated to a static value. function f(flags) { return new RegExp("eee", flags) } ``` When Not To Use It ------------------ If you don’t want to notify regular expressions with no `u` flag, then it’s safe to disable this rule. Version ------- This rule was introduced in ESLint v5.3.0. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/require-unicode-regexp.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/require-unicode-regexp.js) eslint no-extra-label no-extra-label ============== Disallow unnecessary labels 🔧 Fixable Some problems reported by this rule are automatically fixable by the `--fix` [command line](no-extra-label../user-guide/command-line-interface#--fix) option If a loop contains no nested loops or switches, labeling the loop is unnecessary. ``` A: while (a) { break A; } ``` You can achieve the same result by removing the label and using `break` or `continue` without a label. Probably those labels would confuse developers because they expect labels to jump to further. Rule Details ------------ This rule is aimed at eliminating unnecessary labels. Examples of **incorrect** code for this rule: ``` /\*eslint no-extra-label: "error"\*/ A: while (a) { break A; } B: for (let i = 0; i < 10; ++i) { break B; } C: switch (a) { case 0: break C; } ``` Examples of **correct** code for this rule: ``` /\*eslint no-extra-label: "error"\*/ while (a) { break; } for (let i = 0; i < 10; ++i) { break; } switch (a) { case 0: break; } A: { break A; } B: while (a) { while (b) { break B; } } C: switch (a) { case 0: while (b) { break C; } break; } ``` When Not To Use It ------------------ If you don’t want to be notified about usage of labels, then it’s safe to disable this rule. Related Rules ------------- * <no-labels> * <no-label-var> * <no-unused-labels> Version ------- This rule was introduced in ESLint v2.0.0-rc.0. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/no-extra-label.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/no-extra-label.js) eslint no-class-assign no-class-assign =============== Disallow reassigning class members ✅ Recommended The `"extends": "eslint:recommended"` property in a [configuration file](no-class-assign../user-guide/configuring/configuration-files#extending-configuration-files) enables this rule `ClassDeclaration` creates a variable, and we can modify the variable. ``` /\*eslint-env es6\*/ class A { } A = 0; ``` But the modification is a mistake in most cases. Rule Details ------------ This rule is aimed to flag modifying variables of class declarations. Examples of **incorrect** code for this rule: ``` /\*eslint no-class-assign: "error"\*/ /\*eslint-env es6\*/ class A { } A = 0; ``` ``` /\*eslint no-class-assign: "error"\*/ /\*eslint-env es6\*/ A = 0; class A { } ``` ``` /\*eslint no-class-assign: "error"\*/ /\*eslint-env es6\*/ class A { b() { A = 0; } } ``` ``` /\*eslint no-class-assign: "error"\*/ /\*eslint-env es6\*/ let A = class A { b() { A = 0; // `let A` is shadowed by the class name. } } ``` Examples of **correct** code for this rule: ``` /\*eslint no-class-assign: "error"\*/ /\*eslint-env es6\*/ let A = class A { } A = 0; // A is a variable. ``` ``` /\*eslint no-class-assign: "error"\*/ /\*eslint-env es6\*/ let A = class { b() { A = 0; // A is a variable. } } ``` ``` /\*eslint no-class-assign: 2\*/ /\*eslint-env es6\*/ class A { b(A) { A = 0; // A is a parameter. } } ``` When Not To Use It ------------------ If you don’t want to be notified about modifying variables of class declarations, you can safely disable this rule. Version ------- This rule was introduced in ESLint v1.0.0-rc-1. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/no-class-assign.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/no-class-assign.js) eslint max-params max-params ========== Enforce a maximum number of parameters in function definitions Functions that take numerous parameters can be difficult to read and write because it requires the memorization of what each parameter is, its type, and the order they should appear in. As a result, many coders adhere to a convention that caps the number of parameters a function can take. ``` function foo (bar, baz, qux, qxx) { // four parameters, may be too many doSomething(); } ``` Rule Details ------------ This rule enforces a maximum number of parameters allowed in function definitions. Options ------- This rule has a number or object option: * `"max"` (default `3`) enforces a maximum number of parameters in function definitions **Deprecated:** The object property `maximum` is deprecated; please use the object property `max` instead. ### max Examples of **incorrect** code for this rule with the default `{ "max": 3 }` option: ``` /\*eslint max-params: ["error", 3]\*/ /\*eslint-env es6\*/ function foo (bar, baz, qux, qxx) { doSomething(); } let foo = (bar, baz, qux, qxx) => { doSomething(); }; ``` Examples of **correct** code for this rule with the default `{ "max": 3 }` option: ``` /\*eslint max-params: ["error", 3]\*/ /\*eslint-env es6\*/ function foo (bar, baz, qux) { doSomething(); } let foo = (bar, baz, qux) => { doSomething(); }; ``` Related Rules ------------- * <complexity> * <max-depth> * <max-len> * <max-lines> * <max-lines-per-function> * <max-nested-callbacks> * <max-statements> Version ------- This rule was introduced in ESLint v0.0.9. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/max-params.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/max-params.js)
programming_docs
eslint no-self-assign no-self-assign ============== Disallow assignments where both sides are exactly the same ✅ Recommended The `"extends": "eslint:recommended"` property in a [configuration file](no-self-assign../user-guide/configuring/configuration-files#extending-configuration-files) enables this rule Self assignments have no effect, so probably those are an error due to incomplete refactoring. Those indicate that what you should do is still remaining. ``` foo = foo; [bar, baz] = [bar, qiz]; ``` Rule Details ------------ This rule is aimed at eliminating self assignments. Examples of **incorrect** code for this rule: ``` /\*eslint no-self-assign: "error"\*/ foo = foo; [a, b] = [a, b]; [a, ...b] = [x, ...b]; ({a, b} = {a, x}); foo &&= foo; foo ||= foo; foo ??= foo; ``` Examples of **correct** code for this rule: ``` /\*eslint no-self-assign: "error"\*/ foo = bar; [a, b] = [b, a]; // This pattern is warned by the `no-use-before-define` rule. let foo = foo; // The default values have an effect. [foo = 1] = [foo]; // non-self-assignments with properties. obj.a = obj.b; obj.a.b = obj.c.b; obj.a.b = obj.a.c; obj[a] = obj["a"]; // This ignores if there is a function call. obj.a().b = obj.a().b; a().b = a().b; // `&=` and `|=` have an effect on non-integers. foo &= foo; foo |= foo; // Known limitation: this does not support computed properties except single literal or single identifier. obj[a + b] = obj[a + b]; obj["a" + "b"] = obj["a" + "b"]; ``` Options ------- This rule has the option to check properties as well. ``` { "no-self-assign": ["error", {"props": true}] } ``` * `props` - if this is `true`, `no-self-assign` rule warns self-assignments of properties. Default is `true`. ### props Examples of **correct** code with the `{ "props": false }` option: ``` /\*eslint no-self-assign: ["error", {"props": false}]\*/ // self-assignments with properties. obj.a = obj.a; obj.a.b = obj.a.b; obj["a"] = obj["a"]; obj[a] = obj[a]; ``` When Not To Use It ------------------ If you don’t want to notify about self assignments, then it’s safe to disable this rule. Version ------- This rule was introduced in ESLint v2.0.0-rc.0. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/no-self-assign.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/no-self-assign.js) eslint constructor-super constructor-super ================= Require `super()` calls in constructors ✅ Recommended The `"extends": "eslint:recommended"` property in a [configuration file](constructor-super../user-guide/configuring/configuration-files#extending-configuration-files) enables this rule Constructors of derived classes must call `super()`. Constructors of non derived classes must not call `super()`. If this is not observed, the JavaScript engine will raise a runtime error. This rule checks whether or not there is a valid `super()` call. Rule Details ------------ This rule is aimed to flag invalid/missing `super()` calls. Examples of **incorrect** code for this rule: ``` /\*eslint constructor-super: "error"\*/ /\*eslint-env es6\*/ class A { constructor() { super(); // This is a SyntaxError. } } class A extends B { constructor() { } // Would throw a ReferenceError. } // Classes which inherits from a non constructor are always problems. class A extends null { constructor() { super(); // Would throw a TypeError. } } class A extends null { constructor() { } // Would throw a ReferenceError. } ``` Examples of **correct** code for this rule: ``` /\*eslint constructor-super: "error"\*/ /\*eslint-env es6\*/ class A { constructor() { } } class A extends B { constructor() { super(); } } ``` When Not To Use It ------------------ If you don’t want to be notified about invalid/missing `super()` callings in constructors, you can safely disable this rule. Version ------- This rule was introduced in ESLint v0.24.0. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/constructor-super.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/constructor-super.js) eslint no-delete-var no-delete-var ============= Disallow deleting variables ✅ Recommended The `"extends": "eslint:recommended"` property in a [configuration file](no-delete-var../user-guide/configuring/configuration-files#extending-configuration-files) enables this rule The purpose of the `delete` operator is to remove a property from an object. Using the `delete` operator on a variable might lead to unexpected behavior. Rule Details ------------ This rule disallows the use of the `delete` operator on variables. If ESLint parses code in strict mode, the parser (instead of this rule) reports the error. Examples of **incorrect** code for this rule: ``` /\*eslint no-delete-var: "error"\*/ var x; delete x; ``` Version ------- This rule was introduced in ESLint v0.0.9. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/no-delete-var.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/no-delete-var.js) eslint no-plusplus no-plusplus =========== Disallow the unary operators `++` and `--` Because the unary `++` and `--` operators are subject to automatic semicolon insertion, differences in whitespace can change semantics of source code. ``` var i = 10; var j = 20; i ++ j // i = 11, j = 20 ``` ``` var i = 10; var j = 20; i ++ j // i = 10, j = 21 ``` Rule Details ------------ This rule disallows the unary operators `++` and `--`. Examples of **incorrect** code for this rule: ``` /\*eslint no-plusplus: "error"\*/ var foo = 0; foo++; var bar = 42; bar--; for (i = 0; i < l; i++) { return; } ``` Examples of **correct** code for this rule: ``` /\*eslint no-plusplus: "error"\*/ var foo = 0; foo += 1; var bar = 42; bar -= 1; for (i = 0; i < l; i += 1) { return; } ``` Options ------- This rule has an object option. * `"allowForLoopAfterthoughts": true` allows unary operators `++` and `--` in the afterthought (final expression) of a `for` loop. ### allowForLoopAfterthoughts Examples of **correct** code for this rule with the `{ "allowForLoopAfterthoughts": true }` option: ``` /\*eslint no-plusplus: ["error", { "allowForLoopAfterthoughts": true }]\*/ for (i = 0; i < l; i++) { doSomething(i); } for (i = l; i >= 0; i--) { doSomething(i); } for (i = 0, j = l; i < l; i++, j--) { doSomething(i, j); } ``` Examples of **incorrect** code for this rule with the `{ "allowForLoopAfterthoughts": true }` option: ``` /\*eslint no-plusplus: ["error", { "allowForLoopAfterthoughts": true }]\*/ for (i = 0; i < l; j = i++) { doSomething(i, j); } for (i = l; i--;) { doSomething(i); } for (i = 0; i < l;) i++; ``` Version ------- This rule was introduced in ESLint v0.0.9. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/no-plusplus.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/no-plusplus.js) eslint function-paren-newline function-paren-newline ====================== Enforce consistent line breaks inside function parentheses 🔧 Fixable Some problems reported by this rule are automatically fixable by the `--fix` [command line](function-paren-newline../user-guide/command-line-interface#--fix) option Many style guides require or disallow newlines inside of function parentheses. Rule Details ------------ This rule enforces consistent line breaks inside parentheses of function parameters or arguments. ### Options This rule has a single option, which can either be a string or an object. * `"always"` requires line breaks inside all function parentheses. * `"never"` disallows line breaks inside all function parentheses. * `"multiline"` (default) requires linebreaks inside function parentheses if any of the parameters/arguments have a line break between them. Otherwise, it disallows linebreaks. * `"multiline-arguments"` works like `multiline` but allows linebreaks inside function parentheses if there is only one parameter/argument. * `"consistent"` requires consistent usage of linebreaks for each pair of parentheses. It reports an error if one parenthesis in the pair has a linebreak inside it and the other parenthesis does not. * `{ "minItems": value }` requires linebreaks inside function parentheses if the number of parameters/arguments is at least `value`. Otherwise, it disallows linebreaks. Example configurations: ``` { "rules": { "function-paren-newline": ["error", "never"] } } ``` ``` { "rules": { "function-paren-newline": ["error", { "minItems": 3 }] } } ``` Examples of **incorrect** code for this rule with the `"always"` option: ``` /\* eslint function-paren-newline: ["error", "always"] \*/ function foo(bar, baz) {} var foo = function(bar, baz) {}; var foo = (bar, baz) => {}; foo(bar, baz); ``` Examples of **correct** code for this rule with the `"always"` option: ``` /\* eslint function-paren-newline: ["error", "always"] \*/ function foo( bar, baz ) {} var foo = function( bar, baz ) {}; var foo = ( bar, baz ) => {}; foo( bar, baz ); ``` Examples of **incorrect** code for this rule with the `"never"` option: ``` /\* eslint function-paren-newline: ["error", "never"] \*/ function foo( bar, baz ) {} var foo = function( bar, baz ) {}; var foo = ( bar, baz ) => {}; foo( bar, baz ); ``` Examples of **correct** code for this rule with the `"never"` option: ``` /\* eslint function-paren-newline: ["error", "never"] \*/ function foo(bar, baz) {} function foo(bar, baz) {} var foo = function(bar, baz) {}; var foo = (bar, baz) => {}; foo(bar, baz); foo(bar, baz); ``` Examples of **incorrect** code for this rule with the default `"multiline"` option: ``` /\* eslint function-paren-newline: ["error", "multiline"] \*/ function foo(bar, baz ) {} var foo = function( bar, baz ) {}; var foo = ( bar, baz) => {}; foo(bar, baz); foo( function() { return baz; } ); ``` Examples of **correct** code for this rule with the default `"multiline"` option: ``` /\* eslint function-paren-newline: ["error", "multiline"] \*/ function foo(bar, baz) {} var foo = function( bar, baz ) {}; var foo = (bar, baz) => {}; foo(bar, baz, qux); foo( bar, baz, qux ); foo(function() { return baz; }); ``` Examples of **incorrect** code for this rule with the `"consistent"` option: ``` /\* eslint function-paren-newline: ["error", "consistent"] \*/ function foo(bar, baz ) {} var foo = function(bar, baz ) {}; var foo = ( bar, baz) => {}; foo( bar, baz); foo( function() { return baz; }); ``` Examples of **correct** code for this rule with the `"consistent"` option: ``` /\* eslint function-paren-newline: ["error", "consistent"] \*/ function foo(bar, baz) {} var foo = function(bar, baz) {}; var foo = ( bar, baz ) => {}; foo( bar, baz ); foo( function() { return baz; } ); ``` Examples of **incorrect** code for this rule with the `"multiline-arguments"` option: ``` /\* eslint function-paren-newline: ["error", "multiline-arguments"] \*/ function foo(bar, baz ) {} var foo = function(bar, baz ) {}; var foo = ( bar, baz) => {}; foo( bar, baz); foo( bar, qux, baz ); ``` Examples of **correct** code for this rule with the consistent `"multiline-arguments"` option: ``` /\* eslint function-paren-newline: ["error", "multiline-arguments"] \*/ function foo( bar, baz ) {} var foo = function(bar, baz) {}; var foo = ( bar ) => {}; foo( function() { return baz; } ); ``` Examples of **incorrect** code for this rule with the `{ "minItems": 3 }` option: ``` /\* eslint function-paren-newline: ["error", { "minItems": 3 }] \*/ function foo( bar, baz ) {} function foo(bar, baz, qux) {} var foo = function( bar, baz ) {}; var foo = (bar, baz) => {}; foo(bar, baz); ``` Examples of **correct** code for this rule with the `{ "minItems": 3 }` option: ``` /\* eslint function-paren-newline: ["error", { "minItems": 3 }] \*/ function foo(bar, baz) {} var foo = function( bar, baz, qux ) {}; var foo = ( bar, baz, qux ) => {}; foo(bar, baz); foo( bar, baz, qux ); ``` When Not To Use It ------------------ If don’t want to enforce consistent linebreaks inside function parentheses, do not turn on this rule. Version ------- This rule was introduced in ESLint v4.6.0. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/function-paren-newline.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/function-paren-newline.js) eslint no-else-return no-else-return ============== Disallow `else` blocks after `return` statements in `if` statements 🔧 Fixable Some problems reported by this rule are automatically fixable by the `--fix` [command line](no-else-return../user-guide/command-line-interface#--fix) option If an `if` block contains a `return` statement, the `else` block becomes unnecessary. Its contents can be placed outside of the block. ``` function foo() { if (x) { return y; } else { return z; } } ``` Rule Details ------------ This rule is aimed at highlighting an unnecessary block of code following an `if` containing a return statement. As such, it will warn when it encounters an `else` following a chain of `if`s, all of them containing a `return` statement. Options ------- This rule has an object option: * `allowElseIf: true` (default) allows `else if` blocks after a return * `allowElseIf: false` disallows `else if` blocks after a return ### `allowElseIf: true` Examples of **incorrect** code for this rule: ``` /\*eslint no-else-return: "error"\*/ function foo() { if (x) { return y; } else { return z; } } function foo() { if (x) { return y; } else if (z) { return w; } else { return t; } } function foo() { if (x) { return y; } else { var t = "foo"; } return t; } function foo() { if (error) { return 'It failed'; } else { if (loading) { return "It's still loading"; } } } // Two warnings for nested occurrences function foo() { if (x) { if (y) { return y; } else { return x; } } else { return z; } } ``` Examples of **correct** code for this rule: ``` /\*eslint no-else-return: "error"\*/ function foo() { if (x) { return y; } return z; } function foo() { if (x) { return y; } else if (z) { var t = "foo"; } else { return w; } } function foo() { if (x) { if (z) { return y; } } else { return z; } } function foo() { if (error) { return 'It failed'; } else if (loading) { return "It's still loading"; } } ``` ### `allowElseIf: false` Examples of **incorrect** code for this rule: ``` /\*eslint no-else-return: ["error", {allowElseIf: false}]\*/ function foo() { if (error) { return 'It failed'; } else if (loading) { return "It's still loading"; } } ``` Examples of **correct** code for this rule: ``` /\*eslint no-else-return: ["error", {allowElseIf: false}]\*/ function foo() { if (error) { return 'It failed'; } if (loading) { return "It's still loading"; } } ``` Version ------- This rule was introduced in ESLint v0.0.9. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/no-else-return.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/no-else-return.js) eslint eqeqeq eqeqeq ====== Require the use of `===` and `!==` 🔧 Fixable Some problems reported by this rule are automatically fixable by the `--fix` [command line](eqeqeq../user-guide/command-line-interface#--fix) option It is considered good practice to use the type-safe equality operators `===` and `!==` instead of their regular counterparts `==` and `!=`. The reason for this is that `==` and `!=` do type coercion which follows the rather obscure [Abstract Equality Comparison Algorithm](https://www.ecma-international.org/ecma-262/5.1/#sec-11.9.3). For instance, the following statements are all considered `true`: * `[] == false` * `[] == ![]` * `3 == "03"` If one of those occurs in an innocent-looking statement such as `a == b` the actual problem is very difficult to spot. Rule Details ------------ This rule is aimed at eliminating the type-unsafe equality operators. Examples of **incorrect** code for this rule: ``` /\*eslint eqeqeq: "error"\*/ if (x == 42) { } if ("" == text) { } if (obj.getStuff() != undefined) { } ``` The `--fix` option on the command line automatically fixes some problems reported by this rule. A problem is only fixed if one of the operands is a `typeof` expression, or if both operands are literals with the same type. Options ------- ### always The `"always"` option (default) enforces the use of `===` and `!==` in every situation (except when you opt-in to more specific handling of `null` [see below]). Examples of **incorrect** code for the `"always"` option: ``` /\*eslint eqeqeq: ["error", "always"]\*/ a == b foo == true bananas != 1 value == undefined typeof foo == 'undefined' 'hello' != 'world' 0 == 0 true == true foo == null ``` Examples of **correct** code for the `"always"` option: ``` /\*eslint eqeqeq: ["error", "always"]\*/ a === b foo === true bananas !== 1 value === undefined typeof foo === 'undefined' 'hello' !== 'world' 0 === 0 true === true foo === null ``` This rule optionally takes a second argument, which should be an object with the following supported properties: * `"null"`: Customize how this rule treats `null` literals. Possible values: + `always` (default) - Always use === or !==. + `never` - Never use === or !== with `null`. + `ignore` - Do not apply this rule to `null`. ### smart The `"smart"` option enforces the use of `===` and `!==` except for these cases: * Comparing two literal values * Evaluating the value of `typeof` * Comparing against `null` Examples of **incorrect** code for the `"smart"` option: ``` /\*eslint eqeqeq: ["error", "smart"]\*/ // comparing two variables requires === a == b // only one side is a literal foo == true bananas != 1 // comparing to undefined requires === value == undefined ``` Examples of **correct** code for the `"smart"` option: ``` /\*eslint eqeqeq: ["error", "smart"]\*/ typeof foo == 'undefined' 'hello' != 'world' 0 == 0 true == true foo == null ``` ### allow-null **Deprecated:** Instead of using this option use “always” and pass a “null” option property with value “ignore”. This will tell ESLint to always enforce strict equality except when comparing with the `null` literal. ``` ["error", "always", {"null": "ignore"}] ``` When Not To Use It ------------------ If you don’t want to enforce a style for using equality operators, then it’s safe to disable this rule. Version ------- This rule was introduced in ESLint v0.0.2. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/eqeqeq.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/eqeqeq.js) eslint no-self-compare no-self-compare =============== Disallow comparisons where both sides are exactly the same Comparing a variable against itself is usually an error, either a typo or refactoring error. It is confusing to the reader and may potentially introduce a runtime error. The only time you would compare a variable against itself is when you are testing for `NaN`. However, it is far more appropriate to use `typeof x === 'number' && isNaN(x)` or the [Number.isNaN ES2015 function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN) for that use case rather than leaving the reader of the code to determine the intent of self comparison. Rule Details ------------ This error is raised to highlight a potentially confusing and potentially pointless piece of code. There are almost no situations in which you would need to compare something to itself. Examples of **incorrect** code for this rule: ``` /\*eslint no-self-compare: "error"\*/ var x = 10; if (x === x) { x = 20; } ``` Version ------- This rule was introduced in ESLint v0.0.9. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/no-self-compare.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/no-self-compare.js)
programming_docs
eslint consistent-return consistent-return ================= Require `return` statements to either always or never specify values Unlike statically-typed languages which enforce that a function returns a specified type of value, JavaScript allows different code paths in a function to return different types of values. A confusing aspect of JavaScript is that a function returns `undefined` if any of the following are true: * it does not execute a `return` statement before it exits * it executes `return` which does not specify a value explicitly * it executes `return undefined` * it executes `return void` followed by an expression (for example, a function call) * it executes `return` followed by any other expression which evaluates to `undefined` If any code paths in a function return a value explicitly but some code path do not return a value explicitly, it might be a typing mistake, especially in a large function. In the following example: * a code path through the function returns a Boolean value `true` * another code path does not return a value explicitly, therefore returns `undefined` implicitly ``` function doSomething(condition) { if (condition) { return true; } else { return; } } ``` Rule Details ------------ This rule requires `return` statements to either always or never specify values. This rule ignores function definitions where the name begins with an uppercase letter, because constructors (when invoked with the `new` operator) return the instantiated object implicitly if they do not return another object explicitly. Examples of **incorrect** code for this rule: ``` /\*eslint consistent-return: "error"\*/ function doSomething(condition) { if (condition) { return true; } else { return; } } function doSomething(condition) { if (condition) { return true; } } ``` Examples of **correct** code for this rule: ``` /\*eslint consistent-return: "error"\*/ function doSomething(condition) { if (condition) { return true; } else { return false; } } function Foo() { if (!(this instanceof Foo)) { return new Foo(); } this.a = 0; } ``` Options ------- This rule has an object option: * `"treatUndefinedAsUnspecified": false` (default) always either specify values or return `undefined` implicitly only. * `"treatUndefinedAsUnspecified": true` always either specify values or return `undefined` explicitly or implicitly. ### treatUndefinedAsUnspecified Examples of **incorrect** code for this rule with the default `{ "treatUndefinedAsUnspecified": false }` option: ``` /\*eslint consistent-return: ["error", { "treatUndefinedAsUnspecified": false }]\*/ function foo(callback) { if (callback) { return void callback(); } // no return statement } function bar(condition) { if (condition) { return undefined; } // no return statement } ``` Examples of **incorrect** code for this rule with the `{ "treatUndefinedAsUnspecified": true }` option: ``` /\*eslint consistent-return: ["error", { "treatUndefinedAsUnspecified": true }]\*/ function foo(callback) { if (callback) { return void callback(); } return true; } function bar(condition) { if (condition) { return undefined; } return true; } ``` Examples of **correct** code for this rule with the `{ "treatUndefinedAsUnspecified": true }` option: ``` /\*eslint consistent-return: ["error", { "treatUndefinedAsUnspecified": true }]\*/ function foo(callback) { if (callback) { return void callback(); } // no return statement } function bar(condition) { if (condition) { return undefined; } // no return statement } ``` When Not To Use It ------------------ If you want to allow functions to have different `return` behavior depending on code branching, then it is safe to disable this rule. Version ------- This rule was introduced in ESLint v0.4.0. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/consistent-return.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/consistent-return.js) eslint no-whitespace-before-property no-whitespace-before-property ============================= Disallow whitespace before properties 🔧 Fixable Some problems reported by this rule are automatically fixable by the `--fix` [command line](no-whitespace-before-property../user-guide/command-line-interface#--fix) option JavaScript allows whitespace between objects and their properties. However, inconsistent spacing can make code harder to read and can lead to errors. ``` foo. bar .baz . quz ``` Rule Details ------------ This rule disallows whitespace around the dot or before the opening bracket before properties of objects if they are on the same line. This rule allows whitespace when the object and property are on separate lines, as it is common to add newlines to longer chains of properties: ``` foo .bar() .baz() .qux() ``` Examples of **incorrect** code for this rule: ``` /\*eslint no-whitespace-before-property: "error"\*/ foo [bar] foo. bar foo .bar foo. bar. baz foo. bar() .baz() foo .bar(). baz() ``` Examples of **correct** code for this rule: ``` /\*eslint no-whitespace-before-property: "error"\*/ foo.bar foo[bar] foo[ bar ] foo.bar.baz foo .bar().baz() foo .bar() .baz() foo. bar(). baz() ``` When Not To Use It ------------------ Turn this rule off if you do not care about allowing whitespace around the dot or before the opening bracket before properties of objects if they are on the same line. Version ------- This rule was introduced in ESLint v2.0.0-beta.1. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/no-whitespace-before-property.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/no-whitespace-before-property.js) eslint no-multi-spaces no-multi-spaces =============== Disallow multiple spaces 🔧 Fixable Some problems reported by this rule are automatically fixable by the `--fix` [command line](no-multi-spaces../user-guide/command-line-interface#--fix) option Multiple spaces in a row that are not used for indentation are typically mistakes. For example: ``` if(foo === "bar") {} ``` It’s hard to tell, but there are two spaces between `foo` and `===`. Multiple spaces such as this are generally frowned upon in favor of single spaces: ``` if(foo === "bar") {} ``` Rule Details ------------ This rule aims to disallow multiple whitespace around logical expressions, conditional expressions, declarations, array elements, object properties, sequences and function parameters. Examples of **incorrect** code for this rule: ``` /\*eslint no-multi-spaces: "error"\*/ var a = 1; if(foo === "bar") {} a << b var arr = [1, 2]; a ? b: c ``` Examples of **correct** code for this rule: ``` /\*eslint no-multi-spaces: "error"\*/ var a = 1; if(foo === "bar") {} a << b var arr = [1, 2]; a ? b: c ``` Options ------- This rule’s configuration consists of an object with the following properties: * `"ignoreEOLComments": true` (defaults to `false`) ignores multiple spaces before comments that occur at the end of lines * `"exceptions": { "Property": true }` (`"Property"` is the only node specified by default) specifies nodes to ignore ### ignoreEOLComments Examples of **incorrect** code for this rule with the `{ "ignoreEOLComments": false }` (default) option: ``` /\*eslint no-multi-spaces: ["error", { ignoreEOLComments: false }]\*/ var x = 5; // comment var x = 5; /\* multiline \* comment \*/ ``` Examples of **correct** code for this rule with the `{ "ignoreEOLComments": false }` (default) option: ``` /\*eslint no-multi-spaces: ["error", { ignoreEOLComments: false }]\*/ var x = 5; // comment var x = 5; /\* multiline \* comment \*/ ``` Examples of **correct** code for this rule with the `{ "ignoreEOLComments": true }` option: ``` /\*eslint no-multi-spaces: ["error", { ignoreEOLComments: true }]\*/ var x = 5; // comment var x = 5; // comment var x = 5; /\* multiline \* comment \*/ var x = 5; /\* multiline \* comment \*/ ``` ### exceptions To avoid contradictions with other rules that require multiple spaces, this rule has an `exceptions` option to ignore certain nodes. This option is an object that expects property names to be AST node types as defined by [ESTree](https://github.com/estree/estree). The easiest way to determine the node types for `exceptions` is to use [AST Explorer](https://astexplorer.net/) with the espree parser. Only the `Property` node type is ignored by default, because for the [key-spacing](no-multi-spaceskey-spacing) rule some alignment options require multiple spaces in properties of object literals. Examples of **correct** code for the default `"exceptions": { "Property": true }` option: ``` /\*eslint no-multi-spaces: "error"\*/ /\*eslint key-spacing: ["error", { align: "value" }]\*/ var obj = { first: "first", second: "second" }; ``` Examples of **incorrect** code for the `"exceptions": { "Property": false }` option: ``` /\*eslint no-multi-spaces: ["error", { exceptions: { "Property": false } }]\*/ /\*eslint key-spacing: ["error", { align: "value" }]\*/ var obj = { first: "first", second: "second" }; ``` Examples of **correct** code for the `"exceptions": { "BinaryExpression": true }` option: ``` /\*eslint no-multi-spaces: ["error", { exceptions: { "BinaryExpression": true } }]\*/ var a = 1 \* 2; ``` Examples of **correct** code for the `"exceptions": { "VariableDeclarator": true }` option: ``` /\*eslint no-multi-spaces: ["error", { exceptions: { "VariableDeclarator": true } }]\*/ var someVar = 'foo'; var someOtherVar = 'barBaz'; ``` Examples of **correct** code for the `"exceptions": { "ImportDeclaration": true }` option: ``` /\*eslint no-multi-spaces: ["error", { exceptions: { "ImportDeclaration": true } }]\*/ import mod from 'mod'; import someOtherMod from 'some-other-mod'; ``` When Not To Use It ------------------ If you don’t want to check and disallow multiple spaces, then you should turn this rule off. Related Rules ------------- * <key-spacing> * <space-infix-ops> * <space-in-brackets> * <space-in-parens> * <space-after-keywords> * <space-unary-ops> * <space-return-throw-case> Version ------- This rule was introduced in ESLint v0.9.0. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/no-multi-spaces.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/no-multi-spaces.js) eslint unicode-bom unicode-bom =========== Require or disallow Unicode byte order mark (BOM) 🔧 Fixable Some problems reported by this rule are automatically fixable by the `--fix` [command line](unicode-bom../user-guide/command-line-interface#--fix) option The Unicode Byte Order Mark (BOM) is used to specify whether code units are big endian or little endian. That is, whether the most significant or least significant bytes come first. UTF-8 does not require a BOM because byte ordering does not matter when characters are a single byte. Since UTF-8 is the dominant encoding of the web, we make `"never"` the default option. Rule Details ------------ If the `"always"` option is used, this rule requires that files always begin with the Unicode BOM character U+FEFF. If `"never"` is used, files must never begin with U+FEFF. Options ------- This rule has a string option: * `"always"` files must begin with the Unicode BOM * `"never"` (default) files must not begin with the Unicode BOM ### always Example of **correct** code for this rule with the `"always"` option: ``` /\*eslint unicode-bom: ["error", "always"]\*/ U+FEFF var abc; ``` Example of **incorrect** code for this rule with the `"always"` option: ``` /\*eslint unicode-bom: ["error", "always"]\*/ var abc; ``` ### never Example of **correct** code for this rule with the default `"never"` option: ``` /\*eslint unicode-bom: ["error", "never"]\*/ var abc; ``` Example of **incorrect** code for this rule with the `"never"` option: ``` /\*eslint unicode-bom: ["error", "never"]\*/ U+FEFF var abc; ``` When Not To Use It ------------------ If you use some UTF-16 or UTF-32 files and you want to allow a file to optionally begin with a Unicode BOM, you should turn this rule off. Version ------- This rule was introduced in ESLint v2.11.0. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/unicode-bom.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/unicode-bom.js) eslint no-useless-catch no-useless-catch ================ Disallow unnecessary `catch` clauses ✅ Recommended The `"extends": "eslint:recommended"` property in a [configuration file](no-useless-catch../user-guide/configuring/configuration-files#extending-configuration-files) enables this rule A `catch` clause that only rethrows the original error is redundant, and has no effect on the runtime behavior of the program. These redundant clauses can be a source of confusion and code bloat, so it’s better to disallow these unnecessary `catch` clauses. Rule Details ------------ This rule reports `catch` clauses that only `throw` the caught error. Examples of **incorrect** code for this rule: ``` /\*eslint no-useless-catch: "error"\*/ try { doSomethingThatMightThrow(); } catch (e) { throw e; } try { doSomethingThatMightThrow(); } catch (e) { throw e; } finally { cleanUp(); } ``` Examples of **correct** code for this rule: ``` /\*eslint no-useless-catch: "error"\*/ try { doSomethingThatMightThrow(); } catch (e) { doSomethingBeforeRethrow(); throw e; } try { doSomethingThatMightThrow(); } catch (e) { handleError(e); } try { doSomethingThatMightThrow(); } finally { cleanUp(); } ``` When Not To Use It ------------------ If you don’t want to be notified about unnecessary catch clauses, you can safely disable this rule. Version ------- This rule was introduced in ESLint v5.11.0. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/no-useless-catch.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/no-useless-catch.js) eslint no-floating-decimal no-floating-decimal =================== Disallow leading or trailing decimal points in numeric literals 🔧 Fixable Some problems reported by this rule are automatically fixable by the `--fix` [command line](no-floating-decimal../user-guide/command-line-interface#--fix) option Float values in JavaScript contain a decimal point, and there is no requirement that the decimal point be preceded or followed by a number. For example, the following are all valid JavaScript numbers: ``` var num = .5; var num = 2.; var num = -.7; ``` Although not a syntax error, this format for numbers can make it difficult to distinguish between true decimal numbers and the dot operator. For this reason, some recommend that you should always include a number before and after a decimal point to make it clear the intent is to create a decimal number. Rule Details ------------ This rule is aimed at eliminating floating decimal points and will warn whenever a numeric value has a decimal point but is missing a number either before or after it. Examples of **incorrect** code for this rule: ``` /\*eslint no-floating-decimal: "error"\*/ var num = .5; var num = 2.; var num = -.7; ``` Examples of **correct** code for this rule: ``` /\*eslint no-floating-decimal: "error"\*/ var num = 0.5; var num = 2.0; var num = -0.7; ``` When Not To Use It ------------------ If you aren’t concerned about misinterpreting floating decimal point values, then you can safely turn this rule off. Compatibility ------------- * **JSHint**: W008, W047 Version ------- This rule was introduced in ESLint v0.0.6. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/no-floating-decimal.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/no-floating-decimal.js) eslint no-empty no-empty ======== Disallow empty block statements ✅ Recommended The `"extends": "eslint:recommended"` property in a [configuration file](no-empty../user-guide/configuring/configuration-files#extending-configuration-files) enables this rule 💡 hasSuggestions Some problems reported by this rule are manually fixable by editor [suggestions](no-empty../developer-guide/working-with-rules#providing-suggestions) Empty block statements, while not technically errors, usually occur due to refactoring that wasn’t completed. They can cause confusion when reading code. Rule Details ------------ This rule disallows empty block statements. This rule ignores block statements which contain a comment (for example, in an empty `catch` or `finally` block of a `try` statement to indicate that execution should continue regardless of errors). Examples of **incorrect** code for this rule: ``` /\*eslint no-empty: "error"\*/ if (foo) { } while (foo) { } switch(foo) { } try { doSomething(); } catch(ex) { } finally { } ``` Examples of **correct** code for this rule: ``` /\*eslint no-empty: "error"\*/ if (foo) { // empty } while (foo) { /\* empty \*/ } try { doSomething(); } catch (ex) { // continue regardless of error } try { doSomething(); } finally { /\* continue regardless of error \*/ } ``` Options ------- This rule has an object option for exceptions: * `"allowEmptyCatch": true` allows empty `catch` clauses (that is, which do not contain a comment) ### allowEmptyCatch Examples of additional **correct** code for this rule with the `{ "allowEmptyCatch": true }` option: ``` /\* eslint no-empty: ["error", { "allowEmptyCatch": true }] \*/ try { doSomething(); } catch (ex) {} try { doSomething(); } catch (ex) {} finally { /\* continue regardless of error \*/ } ``` When Not To Use It ------------------ If you intentionally use empty block statements then you can disable this rule. Related Rules ------------- * <no-empty-function> Version ------- This rule was introduced in ESLint v0.0.2. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/no-empty.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/no-empty.js) eslint no-redeclare no-redeclare ============ Disallow variable redeclaration ✅ Recommended The `"extends": "eslint:recommended"` property in a [configuration file](no-redeclare../user-guide/configuring/configuration-files#extending-configuration-files) enables this rule In JavaScript, it’s possible to redeclare the same variable name using `var`. This can lead to confusion as to where the variable is actually declared and initialized. Rule Details ------------ This rule is aimed at eliminating variables that have multiple declarations in the same scope. Examples of **incorrect** code for this rule: ``` /\*eslint no-redeclare: "error"\*/ var a = 3; var a = 10; class C { foo() { var b = 3; var b = 10; } static { var c = 3; var c = 10; } } ``` Examples of **correct** code for this rule: ``` /\*eslint no-redeclare: "error"\*/ var a = 3; a = 10; class C { foo() { var b = 3; b = 10; } static { var c = 3; c = 10; } } ``` Options ------- This rule takes one optional argument, an object with a boolean property `"builtinGlobals"`. It defaults to `true`. If set to `true`, this rule also checks redeclaration of built-in globals, such as `Object`, `Array`, `Number`… ### builtinGlobals The `"builtinGlobals"` option will check for redeclaration of built-in globals in global scope. Examples of **incorrect** code for the `{ "builtinGlobals": true }` option: ``` /\*eslint no-redeclare: ["error", { "builtinGlobals": true }]\*/ var Object = 0; ``` Examples of **incorrect** code for the `{ "builtinGlobals": true }` option and the `browser` environment: ``` /\*eslint no-redeclare: ["error", { "builtinGlobals": true }]\*/ /\*eslint-env browser\*/ var top = 0; ``` The `browser` environment has many built-in global variables (for example, `top`). Some of built-in global variables cannot be redeclared. Note that when using the `node` or `commonjs` environments (or `ecmaFeatures.globalReturn`, if using the default parser), the top scope of a program is not actually the global scope, but rather a “module” scope. When this is the case, declaring a variable named after a builtin global is not a redeclaration, but rather a shadowing of the global variable. In that case, the [`no-shadow`](no-redeclareno-shadow) rule with the `"builtinGlobals"` option should be used. Related Rules ------------- * <no-shadow> Version ------- This rule was introduced in ESLint v0.0.9. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/no-redeclare.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/no-redeclare.js)
programming_docs
eslint prefer-object-spread prefer-object-spread ==================== Disallow using Object.assign with an object literal as the first argument and prefer the use of object spread instead 🔧 Fixable Some problems reported by this rule are automatically fixable by the `--fix` [command line](prefer-object-spread../user-guide/command-line-interface#--fix) option When Object.assign is called using an object literal as the first argument, this rule requires using the object spread syntax instead. This rule also warns on cases where an `Object.assign` call is made using a single argument that is an object literal, in this case, the `Object.assign` call is not needed. Introduced in ES2018, object spread is a declarative alternative which may perform better than the more dynamic, imperative `Object.assign`. Rule Details ------------ Examples of **incorrect** code for this rule: ``` /\*eslint prefer-object-spread: "error"\*/ Object.assign({}, foo); Object.assign({}, {foo: 'bar'}); Object.assign({ foo: 'bar'}, baz); Object.assign({}, baz, { foo: 'bar' }); Object.assign({}, { ...baz }); // Object.assign with a single argument that is an object literal Object.assign({}); Object.assign({ foo: bar }); ``` Examples of **correct** code for this rule: ``` /\*eslint prefer-object-spread: "error"\*/ ({ ...foo }); ({ ...baz, foo: 'bar' }); // Any Object.assign call without an object literal as the first argument Object.assign(foo, { bar: baz }); Object.assign(foo, bar); Object.assign(foo, { bar, baz }); Object.assign(foo, { ...baz }); ``` When Not To Use It ------------------ This rule should not be used unless ES2018 is supported in your codebase. Version ------- This rule was introduced in ESLint v5.0.0-alpha.3. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/prefer-object-spread.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/prefer-object-spread.js) eslint default-case-last default-case-last ================= Enforce default clauses in switch statements to be last A `switch` statement can optionally have a `default` clause. If present, it’s usually the last clause, but it doesn’t need to be. It is also allowed to put the `default` clause before all `case` clauses, or anywhere between. The behavior is mostly the same as if it was the last clause. The `default` block will be still executed only if there is no match in the `case` clauses (including those defined after the `default`), but there is also the ability to “fall through” from the `default` clause to the following clause in the list. However, such flow is not common and it would be confusing to the readers. Even if there is no “fall through” logic, it’s still unexpected to see the `default` clause before or between the `case` clauses. By convention, it is expected to be the last clause. If a `switch` statement should have a `default` clause, it’s considered a best practice to define it as the last clause. Rule Details ------------ This rule enforces `default` clauses in `switch` statements to be last. It applies only to `switch` statements that already have a `default` clause. This rule does not enforce the existence of `default` clauses. See [default-case](default-case-lastdefault-case) if you also want to enforce the existence of `default` clauses in `switch` statements. Examples of **incorrect** code for this rule: ``` /\*eslint default-case-last: "error"\*/ switch (foo) { default: bar(); break; case "a": baz(); break; } switch (foo) { case 1: bar(); break; default: baz(); break; case 2: quux(); break; } switch (foo) { case "x": bar(); break; default: case "y": baz(); break; } switch (foo) { default: break; case -1: bar(); break; } switch (foo) { default: doSomethingIfNotZero(); case 0: doSomethingAnyway(); } ``` Examples of **correct** code for this rule: ``` /\*eslint default-case-last: "error"\*/ switch (foo) { case "a": baz(); break; default: bar(); break; } switch (foo) { case 1: bar(); break; case 2: quux(); break; default: baz(); break; } switch (foo) { case "x": bar(); break; case "y": default: baz(); break; } switch (foo) { case -1: bar(); break; } if (foo !== 0) { doSomethingIfNotZero(); } doSomethingAnyway(); ``` Related Rules ------------- * <default-case> Version ------- This rule was introduced in ESLint v7.0.0-alpha.0. Further Reading --------------- [switch - JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch) Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/default-case-last.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/default-case-last.js) eslint func-call-spacing func-call-spacing ================= Require or disallow spacing between function identifiers and their invocations 🔧 Fixable Some problems reported by this rule are automatically fixable by the `--fix` [command line](func-call-spacing../user-guide/command-line-interface#--fix) option When calling a function, developers may insert optional whitespace between the function’s name and the parentheses that invoke it. The following pairs of function calls are equivalent: ``` alert('Hello'); alert ('Hello'); console.log(42); console.log (42); new Date(); new Date (); ``` Rule Details ------------ This rule requires or disallows spaces between the function name and the opening parenthesis that calls it. Options ------- This rule has a string option: * `"never"` (default) disallows space between the function name and the opening parenthesis. * `"always"` requires space between the function name and the opening parenthesis. Further, in `"always"` mode, a second object option is available that contains a single boolean `allowNewlines` property. ### never Examples of **incorrect** code for this rule with the default `"never"` option: ``` /\*eslint func-call-spacing: ["error", "never"]\*/ fn (); fn (); ``` Examples of **correct** code for this rule with the default `"never"` option: ``` /\*eslint func-call-spacing: ["error", "never"]\*/ fn(); ``` ### always Examples of **incorrect** code for this rule with the `"always"` option: ``` /\*eslint func-call-spacing: ["error", "always"]\*/ fn(); fn (); ``` Examples of **correct** code for this rule with the `"always"` option: ``` /\*eslint func-call-spacing: ["error", "always"]\*/ fn (); ``` #### allowNewlines By default, `"always"` does not allow newlines. To permit newlines when in `"always"` mode, set the `allowNewlines` option to `true`. Newlines are never required. Examples of **incorrect** code for this rule with `allowNewlines` option enabled: ``` /\*eslint func-call-spacing: ["error", "always", { "allowNewlines": true }]\*/ fn(); ``` Examples of **correct** code for this rule with the `allowNewlines` option enabled: ``` /\*eslint func-call-spacing: ["error", "always", { "allowNewlines": true }]\*/ fn (); // Newlines are never required. fn (); ``` When Not To Use It ------------------ This rule can safely be turned off if your project does not care about enforcing a consistent style for spacing within function calls. Compatibility ------------- * **JSCS**: [disallowSpacesInCallExpression](https://jscs-dev.github.io/rule/disallowSpacesInCallExpression) * **JSCS**: [requireSpacesInCallExpression](https://jscs-dev.github.io/rule/requireSpacesInCallExpression) Related Rules ------------- * <no-spaced-func> Version ------- This rule was introduced in ESLint v3.3.0. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/func-call-spacing.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/func-call-spacing.js) eslint wrap-regex wrap-regex ========== Require parenthesis around regex literals 🔧 Fixable Some problems reported by this rule are automatically fixable by the `--fix` [command line](wrap-regex../user-guide/command-line-interface#--fix) option When a regular expression is used in certain situations, it can end up looking like a division operator. For example: ``` function a() { return /foo/.test("bar"); } ``` Rule Details ------------ This is used to disambiguate the slash operator and facilitates more readable code. Example of **incorrect** code for this rule: ``` /\*eslint wrap-regex: "error"\*/ function a() { return /foo/.test("bar"); } ``` Example of **correct** code for this rule: ``` /\*eslint wrap-regex: "error"\*/ function a() { return (/foo/).test("bar"); } ``` Version ------- This rule was introduced in ESLint v0.1.0. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/wrap-regex.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/wrap-regex.js) eslint brace-style brace-style =========== Enforce consistent brace style for blocks 🔧 Fixable Some problems reported by this rule are automatically fixable by the `--fix` [command line](brace-style../user-guide/command-line-interface#--fix) option Brace style is closely related to [indent style](https://en.wikipedia.org/wiki/Indent_style) in programming and describes the placement of braces relative to their control statement and body. There are probably a dozen, if not more, brace styles in the world. The *one true brace style* is one of the most common brace styles in JavaScript, in which the opening brace of a block is placed on the same line as its corresponding statement or declaration. For example: ``` if (foo) { bar(); } else { baz(); } ``` One common variant of one true brace style is called Stroustrup, in which the `else` statements in an `if-else` construct, as well as `catch` and `finally`, must be on its own line after the preceding closing brace. For example: ``` if (foo) { bar(); } else { baz(); } ``` Another style is called [Allman](https://en.wikipedia.org/wiki/Indent_style#Allman_style), in which all the braces are expected to be on their own lines without any extra indentation. For example: ``` if (foo) { bar(); } else { baz(); } ``` While no style is considered better than the other, most developers agree that having a consistent style throughout a project is important for its long-term maintainability. Rule Details ------------ This rule enforces consistent brace style for blocks. Options ------- This rule has a string option: * `"1tbs"` (default) enforces one true brace style * `"stroustrup"` enforces Stroustrup style * `"allman"` enforces Allman style This rule has an object option for an exception: * `"allowSingleLine": true` (default `false`) allows the opening and closing braces for a block to be on the *same* line ### 1tbs Examples of **incorrect** code for this rule with the default `"1tbs"` option: ``` /\*eslint brace-style: "error"\*/ function foo() { return true; } if (foo) { bar(); } try { somethingRisky(); } catch(e) { handleError(); } if (foo) { bar(); } else { baz(); } class C { static { foo(); } } ``` Examples of **correct** code for this rule with the default `"1tbs"` option: ``` /\*eslint brace-style: "error"\*/ function foo() { return true; } if (foo) { bar(); } if (foo) { bar(); } else { baz(); } try { somethingRisky(); } catch(e) { handleError(); } class C { static { foo(); } } // when there are no braces, there are no problems if (foo) bar(); else if (baz) boom(); ``` Examples of **correct** code for this rule with the `"1tbs", { "allowSingleLine": true }` options: ``` /\*eslint brace-style: ["error", "1tbs", { "allowSingleLine": true }]\*/ function nop() { return; } if (foo) { bar(); } if (foo) { bar(); } else { baz(); } try { somethingRisky(); } catch(e) { handleError(); } if (foo) { baz(); } else { boom(); } if (foo) { baz(); } else if (bar) { boom(); } if (foo) { baz(); } else if (bar) { boom(); } if (foo) { baz(); } else if (bar) { boom(); } try { somethingRisky(); } catch(e) { handleError(); } class C { static { foo(); } } class D { static { foo(); } } ``` ### stroustrup Examples of **incorrect** code for this rule with the `"stroustrup"` option: ``` /\*eslint brace-style: ["error", "stroustrup"]\*/ function foo() { return true; } if (foo) { bar(); } try { somethingRisky(); } catch(e) { handleError(); } class C { static { foo(); } } if (foo) { bar(); } else { baz(); } ``` Examples of **correct** code for this rule with the `"stroustrup"` option: ``` /\*eslint brace-style: ["error", "stroustrup"]\*/ function foo() { return true; } if (foo) { bar(); } if (foo) { bar(); } else { baz(); } try { somethingRisky(); } catch(e) { handleError(); } class C { static { foo(); } } // when there are no braces, there are no problems if (foo) bar(); else if (baz) boom(); ``` Examples of **correct** code for this rule with the `"stroustrup", { "allowSingleLine": true }` options: ``` /\*eslint brace-style: ["error", "stroustrup", { "allowSingleLine": true }]\*/ function nop() { return; } if (foo) { bar(); } if (foo) { bar(); } else { baz(); } try { somethingRisky(); } catch(e) { handleError(); } class C { static { foo(); } } class D { static { foo(); } } ``` ### allman Examples of **incorrect** code for this rule with the `"allman"` option: ``` /\*eslint brace-style: ["error", "allman"]\*/ function foo() { return true; } if (foo) { bar(); } try { somethingRisky(); } catch(e) { handleError(); } class C { static { foo(); } } if (foo) { bar(); } else { baz(); } ``` Examples of **correct** code for this rule with the `"allman"` option: ``` /\*eslint brace-style: ["error", "allman"]\*/ function foo() { return true; } if (foo) { bar(); } if (foo) { bar(); } else { baz(); } try { somethingRisky(); } catch(e) { handleError(); } class C { static { foo(); } } // when there are no braces, there are no problems if (foo) bar(); else if (baz) boom(); ``` Examples of **correct** code for this rule with the `"allman", { "allowSingleLine": true }` options: ``` /\*eslint brace-style: ["error", "allman", { "allowSingleLine": true }]\*/ function nop() { return; } if (foo) { bar(); } if (foo) { bar(); } else { baz(); } try { somethingRisky(); } catch(e) { handleError(); } class C { static { foo(); } static { foo(); } } class D { static { foo(); } } ``` When Not To Use It ------------------ If you don’t want to enforce a particular brace style, don’t enable this rule. Related Rules ------------- * <block-spacing> * <space-before-blocks> Version ------- This rule was introduced in ESLint v0.0.7. Further Reading --------------- [Indentation style - Wikipedia](https://en.wikipedia.org/wiki/Indent_style) Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/brace-style.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/brace-style.js) eslint no-tabs no-tabs ======= Disallow all tabs Some style guides don’t allow the use of tab characters at all, including within comments. Rule Details ------------ This rule looks for tabs anywhere inside a file: code, comments or anything else. Examples of **incorrect** code for this rule: ``` var a \t= 2; /\*\* \* \t\t it's a test function \*/ function test(){} var x = 1; // \t test ``` Examples of **correct** code for this rule: ``` var a = 2; /\*\* \* it's a test function \*/ function test(){} var x = 1; // test ``` ### Options This rule has an optional object option with the following properties: * `allowIndentationTabs` (default: false): If this is set to true, then the rule will not report tabs used for indentation. #### allowIndentationTabs Examples of **correct** code for this rule with the `allowIndentationTabs: true` option: ``` /\* eslint no-tabs: ["error", { allowIndentationTabs: true }] \*/ function test() { \tdoSomething(); } \t// comment with leading indentation tab ``` When Not To Use It ------------------ If you have established a standard where having tabs is fine, then you can disable this rule. Compatibility ------------- * **JSCS**: [disallowTabs](https://jscs-dev.github.io/rule/disallowTabs) Version ------- This rule was introduced in ESLint v3.2.0. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/no-tabs.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/no-tabs.js) eslint prefer-spread prefer-spread ============= Require spread operators instead of `.apply()` Before ES2015, one must use `Function.prototype.apply()` to call variadic functions. ``` var args = [1, 2, 3, 4]; Math.max.apply(Math, args); ``` In ES2015, one can use spread syntax to call variadic functions. ``` /\*eslint-env es6\*/ var args = [1, 2, 3, 4]; Math.max(...args); ``` Rule Details ------------ This rule is aimed to flag usage of `Function.prototype.apply()` in situations where spread syntax could be used instead. Examples -------- Examples of **incorrect** code for this rule: ``` /\*eslint prefer-spread: "error"\*/ foo.apply(undefined, args); foo.apply(null, args); obj.foo.apply(obj, args); ``` Examples of **correct** code for this rule: ``` /\*eslint prefer-spread: "error"\*/ // Using spread syntax foo(...args); obj.foo(...args); // The `this` binding is different. foo.apply(obj, args); obj.foo.apply(null, args); obj.foo.apply(otherObj, args); // The argument list is not variadic. // Those are warned by the `no-useless-call` rule. foo.apply(undefined, [1, 2, 3]); foo.apply(null, [1, 2, 3]); obj.foo.apply(obj, [1, 2, 3]); ``` Known limitations: This rule analyzes code statically to check whether or not the `this` argument is changed. So, if the `this` argument is computed in a dynamic expression, this rule cannot detect a violation. ``` /\*eslint prefer-spread: "error"\*/ // This warns. a[i++].foo.apply(a[i++], args); // This does not warn. a[++i].foo.apply(a[i], args); ``` When Not To Use It ------------------ This rule should not be used in ES3/5 environments. In ES2015 (ES6) or later, if you don’t want to be notified about `Function.prototype.apply()` callings, you can safely disable this rule. Related Rules ------------- * <no-useless-call> Version ------- This rule was introduced in ESLint v1.0.0-rc-1. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/prefer-spread.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/prefer-spread.js) eslint no-cond-assign no-cond-assign ============== Disallow assignment operators in conditional expressions ✅ Recommended The `"extends": "eslint:recommended"` property in a [configuration file](no-cond-assign../user-guide/configuring/configuration-files#extending-configuration-files) enables this rule In conditional statements, it is very easy to mistype a comparison operator (such as `==`) as an assignment operator (such as `=`). For example: ``` // Check the user's job title if (user.jobTitle = "manager") { // user.jobTitle is now incorrect } ``` There are valid reasons to use assignment operators in conditional statements. However, it can be difficult to tell whether a specific assignment was intentional. Rule Details ------------ This rule disallows ambiguous assignment operators in test conditions of `if`, `for`, `while`, and `do...while` statements. Options ------- This rule has a string option: * `"except-parens"` (default) allows assignments in test conditions *only if* they are enclosed in parentheses (for example, to allow reassigning a variable in the test of a `while` or `do...while` loop) * `"always"` disallows all assignments in test conditions ### except-parens Examples of **incorrect** code for this rule with the default `"except-parens"` option: ``` /\*eslint no-cond-assign: "error"\*/ // Unintentional assignment var x; if (x = 0) { var b = 1; } // Practical example that is similar to an error function setHeight(someNode) { "use strict"; do { someNode.height = "100px"; } while (someNode = someNode.parentNode); } ``` Examples of **correct** code for this rule with the default `"except-parens"` option: ``` /\*eslint no-cond-assign: "error"\*/ // Assignment replaced by comparison var x; if (x === 0) { var b = 1; } // Practical example that wraps the assignment in parentheses function setHeight(someNode) { "use strict"; do { someNode.height = "100px"; } while ((someNode = someNode.parentNode)); } // Practical example that wraps the assignment and tests for 'null' function setHeight(someNode) { "use strict"; do { someNode.height = "100px"; } while ((someNode = someNode.parentNode) !== null); } ``` ### always Examples of **incorrect** code for this rule with the `"always"` option: ``` /\*eslint no-cond-assign: ["error", "always"]\*/ // Unintentional assignment var x; if (x = 0) { var b = 1; } // Practical example that is similar to an error function setHeight(someNode) { "use strict"; do { someNode.height = "100px"; } while (someNode = someNode.parentNode); } // Practical example that wraps the assignment in parentheses function setHeight(someNode) { "use strict"; do { someNode.height = "100px"; } while ((someNode = someNode.parentNode)); } // Practical example that wraps the assignment and tests for 'null' function setHeight(someNode) { "use strict"; do { someNode.height = "100px"; } while ((someNode = someNode.parentNode) !== null); } ``` Examples of **correct** code for this rule with the `"always"` option: ``` /\*eslint no-cond-assign: ["error", "always"]\*/ // Assignment replaced by comparison var x; if (x === 0) { var b = 1; } ``` Related Rules ------------- * <no-extra-parens> Version ------- This rule was introduced in ESLint v0.0.9. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/no-cond-assign.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/no-cond-assign.js)
programming_docs
eslint spaced-comment spaced-comment ============== Enforce consistent spacing after the `//` or `/*` in a comment 🔧 Fixable Some problems reported by this rule are automatically fixable by the `--fix` [command line](spaced-comment../user-guide/command-line-interface#--fix) option Some style guides require or disallow a whitespace immediately after the initial `//` or `/*` of a comment. Whitespace after the `//` or `/*` makes it easier to read text in comments. On the other hand, commenting out code is easier without having to put a whitespace right after the `//` or `/*`. Rule Details ------------ This rule will enforce consistency of spacing after the start of a comment `//` or `/*`. It also provides several exceptions for various documentation styles. Options ------- The rule takes two options. * The first is a string which be either `"always"` or `"never"`. The default is `"always"`. + If `"always"` then the `//` or `/*` must be followed by at least one whitespace. + If `"never"` then there should be no whitespace following. * This rule can also take a 2nd option, an object with any of the following keys: `"exceptions"` and `"markers"`. + The `"exceptions"` value is an array of string patterns which are considered exceptions to the rule. The rule will not warn when the pattern starts from the beginning of the comment and repeats until the end of the line or `*/` if the comment is a single line comment. Please note that exceptions are ignored if the first argument is `"never"`. ``` "spaced-comment": ["error", "always", { "exceptions": ["-", "+"] }] ``` + The `"markers"` value is an array of string patterns which are considered markers for docblock-style comments, such as an additional `/`, used to denote documentation read by doxygen, vsdoc, etc. which must have additional characters. The `"markers"` array will apply regardless of the value of the first argument, e.g. `"always"` or `"never"`. ``` "spaced-comment": ["error", "always", { "markers": ["/"] }] ``` The difference between a marker and an exception is that a marker only appears at the beginning of the comment whereas exceptions can occur anywhere in the comment string. You can also define separate exceptions and markers for block and line comments. The `"block"` object can have an additional key `"balanced"`, a boolean that specifies if inline block comments should have balanced spacing. The default value is `false`. * If `"balanced": true` and `"always"` then the `/*` must be followed by at least one whitespace, and the `*/` must be preceded by at least one whitespace. * If `"balanced": true` and `"never"` then there should be no whitespace following `/*` or preceding `*/`. * If `"balanced": false` then balanced whitespace is not enforced. ``` "spaced-comment": ["error", "always", { "line": { "markers": ["/"], "exceptions": ["-", "+"] }, "block": { "markers": ["!"], "exceptions": ["\*"], "balanced": true } }] ``` ### always Examples of **incorrect** code for this rule with the `"always"` option: ``` /\*eslint spaced-comment: ["error", "always"]\*/ //This is a comment with no whitespace at the beginning /\*This is a comment with no whitespace at the beginning \*/ ``` ``` /\* eslint spaced-comment: ["error", "always", { "block": { "balanced": true } }] \*/ /\* This is a comment with whitespace at the beginning but not the end\*/ ``` Examples of **correct** code for this rule with the `"always"` option: ``` /\* eslint spaced-comment: ["error", "always"] \*/ // This is a comment with a whitespace at the beginning /\* This is a comment with a whitespace at the beginning \*/ /\* \* This is a comment with a whitespace at the beginning \*/ /\* This comment has a newline \*/ ``` ``` /\* eslint spaced-comment: ["error", "always"] \*/ /\*\* \* I am jsdoc \*/ ``` ### never Examples of **incorrect** code for this rule with the `"never"` option: ``` /\*eslint spaced-comment: ["error", "never"]\*/ // This is a comment with a whitespace at the beginning /\* This is a comment with a whitespace at the beginning \*/ /\* \nThis is a comment with a whitespace at the beginning \*/ ``` ``` /\*eslint spaced-comment: ["error", "never", { "block": { "balanced": true } }]\*/ /\*This is a comment with whitespace at the end \*/ ``` Examples of **correct** code for this rule with the `"never"` option: ``` /\*eslint spaced-comment: ["error", "never"]\*/ /\*This is a comment with no whitespace at the beginning \*/ ``` ``` /\*eslint spaced-comment: ["error", "never"]\*/ /\*\* \* I am jsdoc \*/ ``` ### exceptions Examples of **incorrect** code for this rule with the `"always"` option combined with `"exceptions"`: ``` /\* eslint spaced-comment: ["error", "always", { "block": { "exceptions": ["-"] } }] \*/ //-------------- // Comment block //-------------- ``` ``` /\* eslint spaced-comment: ["error", "always", { "exceptions": ["-", "+"] }] \*/ //------++++++++ // Comment block //------++++++++ ``` ``` /\* eslint spaced-comment: ["error", "always", { "exceptions": ["-", "+"] }] \*/ /\*------++++++++\*/ /\* Comment block \*/ /\*------++++++++\*/ ``` ``` /\* eslint spaced-comment: ["error", "always", { "line": { "exceptions": ["-+"] } }] \*/ /\*-+-+-+-+-+-+-+\*/ // Comment block /\*-+-+-+-+-+-+-+\*/ ``` ``` /\* eslint spaced-comment: ["error", "always", { "block": { "exceptions": ["\*"] } }] \*/ /\*\*\*\*\*\*\*\* COMMENT \*\*\*\*\*\*\*/ ``` Examples of **correct** code for this rule with the `"always"` option combined with `"exceptions"`: ``` /\* eslint spaced-comment: ["error", "always", { "exceptions": ["-"] }] \*/ //-------------- // Comment block //-------------- ``` ``` /\* eslint spaced-comment: ["error", "always", { "line": { "exceptions": ["-"] } }] \*/ //-------------- // Comment block //-------------- ``` ``` /\* eslint spaced-comment: ["error", "always", { "exceptions": ["\*"] }] \*/ /\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\* \* Comment block \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*/ ``` ``` /\* eslint spaced-comment: ["error", "always", { "exceptions": ["-+"] }] \*/ //-+-+-+-+-+-+-+ // Comment block //-+-+-+-+-+-+-+ /\*-+-+-+-+-+-+-+\*/ // Comment block /\*-+-+-+-+-+-+-+\*/ ``` ``` /\* eslint spaced-comment: ["error", "always", { "block": { "exceptions": ["-+"] } }] \*/ /\*-+-+-+-+-+-+-+\*/ // Comment block /\*-+-+-+-+-+-+-+\*/ ``` ``` /\* eslint spaced-comment: ["error", "always", { "block": { "exceptions": ["\*"] } }] \*/ /\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*/ /\*\*\*\*\*\*\*\* COMMENT \*\*\*\*\*\*\*/ ``` ### markers Examples of **incorrect** code for this rule with the `"always"` option combined with `"markers"`: ``` /\* eslint spaced-comment: ["error", "always", { "markers": ["/"] }] \*/ ///This is a comment with a marker but without whitespace ``` ``` /\*eslint spaced-comment: ["error", "always", { "block": { "markers": ["!"], "balanced": true } }]\*/ /\*! This is a comment with a marker but without whitespace at the end\*/ ``` ``` /\*eslint spaced-comment: ["error", "never", { "block": { "markers": ["!"], "balanced": true } }]\*/ /\*!This is a comment with a marker but with whitespace at the end \*/ ``` Examples of **correct** code for this rule with the `"always"` option combined with `"markers"`: ``` /\* eslint spaced-comment: ["error", "always", { "markers": ["/"] }] \*/ /// This is a comment with a marker ``` ``` /\*eslint spaced-comment: ["error", "never", { "markers": ["!<"] }]\*/ //!<This is a line comment with a marker /\*!<this is a block comment with a marker subsequent lines are ignored \*/ ``` ``` /\* eslint spaced-comment: ["error", "always", { "markers": ["global"] }] \*/ /\*global ABC\*/ ``` Related Rules ------------- * <spaced-line-comment> Version ------- This rule was introduced in ESLint v0.23.0. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/spaced-comment.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/spaced-comment.js) eslint key-spacing key-spacing =========== Enforce consistent spacing between keys and values in object literal properties 🔧 Fixable Some problems reported by this rule are automatically fixable by the `--fix` [command line](key-spacing../user-guide/command-line-interface#--fix) option This rule enforces spacing around the colon in object literal properties. It can verify each property individually, or it can ensure horizontal alignment of adjacent properties in an object literal. Rule Details ------------ This rule enforces consistent spacing between keys and values in object literal properties. In the case of long lines, it is acceptable to add a new line wherever whitespace is allowed. Options ------- This rule has an object option: * `"beforeColon": false (default) | true` + `false`: disallows spaces between the key and the colon in object literals. + `true`: requires at least one space between the key and the colon in object literals. * `"afterColon": true (default) | false` + `true`: requires at least one space between the colon and the value in object literals. + `false`: disallows spaces between the colon and the value in object literals. * `"mode": "strict" (default) | "minimum"` + `"strict"`: enforces exactly one space before or after colons in object literals. + `"minimum"`: enforces one or more spaces before or after colons in object literals. * `"align": "value" | "colon"` + `"value"`: enforces horizontal alignment of values in object literals. + `"colon"` enforces horizontal alignment of both colons and values in object literals. * `"align"` with an object value allows for fine-grained spacing when values are being aligned in object literals. * `"singleLine"` specifies a spacing style for single-line object literals. * `"multiLine"` specifies a spacing style for multi-line object literals. Please note that you can either use the top-level options or the grouped options (`singleLine` and `multiLine`) but not both. ### beforeColon Examples of **incorrect** code for this rule with the default `{ "beforeColon": false }` option: ``` /\*eslint key-spacing: ["error", { "beforeColon": false }]\*/ var obj = { "foo" : 42 }; ``` Examples of **correct** code for this rule with the default `{ "beforeColon": false }` option: ``` /\*eslint key-spacing: ["error", { "beforeColon": false }]\*/ var obj = { "foo": 42 }; ``` Examples of **incorrect** code for this rule with the `{ "beforeColon": true }` option: ``` /\*eslint key-spacing: ["error", { "beforeColon": true }]\*/ var obj = { "foo": 42 }; ``` Examples of **correct** code for this rule with the `{ "beforeColon": true }` option: ``` /\*eslint key-spacing: ["error", { "beforeColon": true }]\*/ var obj = { "foo" : 42 }; ``` ### afterColon Examples of **incorrect** code for this rule with the default `{ "afterColon": true }` option: ``` /\*eslint key-spacing: ["error", { "afterColon": true }]\*/ var obj = { "foo":42 }; ``` Examples of **correct** code for this rule with the default `{ "afterColon": true }` option: ``` /\*eslint key-spacing: ["error", { "afterColon": true }]\*/ var obj = { "foo": 42 }; ``` Examples of **incorrect** code for this rule with the `{ "afterColon": false }` option: ``` /\*eslint key-spacing: ["error", { "afterColon": false }]\*/ var obj = { "foo": 42 }; ``` Examples of **correct** code for this rule with the `{ "afterColon": false }` option: ``` /\*eslint key-spacing: ["error", { "afterColon": false }]\*/ var obj = { "foo":42 }; ``` ### mode Examples of **incorrect** code for this rule with the default `{ "mode": "strict" }` option: ``` /\*eslint key-spacing: ["error", { "mode": "strict" }]\*/ call({ foobar: 42, bat: 2 \* 2 }); ``` Examples of **correct** code for this rule with the default `{ "mode": "strict" }` option: ``` /\*eslint key-spacing: ["error", { "mode": "strict" }]\*/ call({ foobar: 42, bat: 2 \* 2 }); ``` Examples of **correct** code for this rule with the `{ "mode": "minimum" }` option: ``` /\*eslint key-spacing: ["error", { "mode": "minimum" }]\*/ call({ foobar: 42, bat: 2 \* 2 }); ``` ### align Examples of **incorrect** code for this rule with the `{ "align": "value" }` option: ``` /\*eslint key-spacing: ["error", { "align": "value" }]\*/ var obj = { a: value, bcde: 42, fg : foo() }; ``` Examples of **correct** code for this rule with the `{ "align": "value" }` option: ``` /\*eslint key-spacing: ["error", { "align": "value" }]\*/ var obj = { a: value, bcde: 42, fg: foo(), h: function() { return this.a; }, ijkl: 'Non-consecutive lines form a new group' }; var obj = { a: "foo", longPropertyName: "bar" }; ``` Examples of **incorrect** code for this rule with the `{ "align": "colon" }` option: ``` /\*eslint key-spacing: ["error", { "align": "colon" }]\*/ call({ foobar: 42, bat: 2 \* 2 }); ``` Examples of **correct** code for this rule with the `{ "align": "colon" }` option: ``` /\*eslint key-spacing: ["error", { "align": "colon" }]\*/ call({ foobar: 42, bat : 2 \* 2 }); ``` ### align The `align` option can take additional configuration through the `beforeColon`, `afterColon`, `mode`, and `on` options. If `align` is defined as an object, but not all of the parameters are provided, undefined parameters will default to the following: ``` // Defaults align: { "beforeColon": false, "afterColon": true, "on": "colon", "mode": "strict" } ``` Examples of **correct** code for this rule with sample `{ "align": { } }` options: ``` /\*eslint key-spacing: ["error", { "align": { "beforeColon": true, "afterColon": true, "on": "colon" } }]\*/ var obj = { "one" : 1, "seven" : 7 } ``` ``` /\*eslint key-spacing: ["error", { "align": { "beforeColon": false, "afterColon": false, "on": "value" } }]\*/ var obj = { "one": 1, "seven":7 } ``` ### align and multiLine The `multiLine` and `align` options can differ, which allows for fine-tuned control over the `key-spacing` of your files. `align` will **not** inherit from `multiLine` if `align` is configured as an object. `multiLine` is used any time an object literal spans multiple lines. The `align` configuration is used when there is a group of properties in the same object. For example: ``` var myObj = { key1: 1, // uses multiLine key2: 2, // uses align (when defined) key3: 3, // uses align (when defined) key4: 4 // uses multiLine } ``` Examples of **incorrect** code for this rule with sample `{ "align": { }, "multiLine": { } }` options: ``` /\*eslint key-spacing: ["error", { "multiLine": { "beforeColon": false, "afterColon":true }, "align": { "beforeColon": true, "afterColon": true, "on": "colon" } }]\*/ var obj = { "myObjectFunction": function() { // Do something }, "one" : 1, "seven" : 7 } ``` Examples of **correct** code for this rule with sample `{ "align": { }, "multiLine": { } }` options: ``` /\*eslint key-spacing: ["error", { "multiLine": { "beforeColon": false, "afterColon": true }, "align": { "beforeColon": true, "afterColon": true, "on": "colon" } }]\*/ var obj = { "myObjectFunction": function() { // Do something // }, // These are two separate groups, so no alignment between `myObjectFunction` and `one` "one" : 1, "seven" : 7 // `one` and `seven` are in their own group, and therefore aligned } ``` ### singleLine and multiLine Examples of **correct** code for this rule with sample `{ "singleLine": { }, "multiLine": { } }` options: ``` /\*eslint "key-spacing": [2, { "singleLine": { "beforeColon": false, "afterColon": true }, "multiLine": { "beforeColon": true, "afterColon": true, "align": "colon" } }]\*/ var obj = { one: 1, "two": 2, three: 3 }; var obj2 = { "two" : 2, three : 3 }; ``` When Not To Use It ------------------ If you have another convention for property spacing that might not be consistent with the available options, or if you want to permit multiple styles concurrently you can safely disable this rule. Version ------- This rule was introduced in ESLint v0.9.0. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/key-spacing.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/key-spacing.js) eslint strict strict ====== Require or disallow strict mode directives 🔧 Fixable Some problems reported by this rule are automatically fixable by the `--fix` [command line](strict../user-guide/command-line-interface#--fix) option A strict mode directive is a `"use strict"` literal at the beginning of a script or function body. It enables strict mode semantics. When a directive occurs in global scope, strict mode applies to the entire script: ``` "use strict"; // strict mode function foo() { // strict mode } ``` When a directive occurs at the beginning of a function body, strict mode applies only to that function, including all contained functions: ``` function foo() { "use strict"; // strict mode } function foo2() { // not strict mode }; (function() { "use strict"; function bar() { // strict mode } }()); ``` In the **CommonJS** module system, a hidden function wraps each module and limits the scope of a “global” strict mode directive. In **ECMAScript** modules, which always have strict mode semantics, the directives are unnecessary. Rule Details ------------ This rule requires or disallows strict mode directives. This rule disallows strict mode directives, no matter which option is specified, if ESLint configuration specifies either of the following as [parser options](strict../user-guide/configuring/language-options#specifying-parser-options): * `"sourceType": "module"` that is, files are **ECMAScript** modules * `"impliedStrict": true` property in the `ecmaFeatures` object This rule disallows strict mode directives, no matter which option is specified, in functions with non-simple parameter lists (for example, parameter lists with default parameter values) because that is a syntax error in **ECMAScript 2016** and later. See the examples of the [function](#function) option. This rule does not apply to class static blocks, no matter which option is specified, because class static blocks do not have directives. Therefore, a `"use strict"` statement in a class static block is not a directive, and will be reported by the [no-unused-expressions](strictno-unused-expressions) rule. The `--fix` option on the command line does not insert new `"use strict"` statements, but only removes unneeded statements. Options ------- This rule has a string option: * `"safe"` (default) corresponds either of the following options: + `"global"` if ESLint considers a file to be a **CommonJS** module + `"function"` otherwise * `"global"` requires one strict mode directive in the global scope (and disallows any other strict mode directives) * `"function"` requires one strict mode directive in each top-level function declaration or expression (and disallows any other strict mode directives) * `"never"` disallows strict mode directives ### safe The `"safe"` option corresponds to the `"global"` option if ESLint considers a file to be a **Node.js** or **CommonJS** module because the configuration specifies either of the following: * `node` or `commonjs` [environments](strict../user-guide/configuring/language-options#specifying-environments) * `"globalReturn": true` property in the `ecmaFeatures` object of [parser options](strict../user-guide/configuring/language-options#specifying-parser-options) Otherwise the `"safe"` option corresponds to the `"function"` option. Note that if `"globalReturn": false` is explicitly specified in the configuration, the `"safe"` option will correspond to the `"function"` option regardless of the specified environment. ### global Examples of **incorrect** code for this rule with the `"global"` option: ``` /\*eslint strict: ["error", "global"]\*/ function foo() { } ``` ``` /\*eslint strict: ["error", "global"]\*/ function foo() { "use strict"; } ``` ``` /\*eslint strict: ["error", "global"]\*/ "use strict"; function foo() { "use strict"; } ``` Examples of **correct** code for this rule with the `"global"` option: ``` /\*eslint strict: ["error", "global"]\*/ "use strict"; function foo() { } ``` ### function This option ensures that all function bodies are strict mode code, while global code is not. Particularly if a build step concatenates multiple scripts, a strict mode directive in global code of one script could unintentionally enable strict mode in another script that was not intended to be strict code. Examples of **incorrect** code for this rule with the `"function"` option: ``` /\*eslint strict: ["error", "function"]\*/ "use strict"; function foo() { } ``` ``` /\*eslint strict: ["error", "function"]\*/ function foo() { } (function() { function bar() { "use strict"; } }()); ``` ``` /\*eslint strict: ["error", "function"]\*/ /\*eslint-env es6\*/ // Illegal "use strict" directive in function with non-simple parameter list. // This is a syntax error since ES2016. function foo(a = 1) { "use strict"; } // We cannot write "use strict" directive in this function. // So we have to wrap this function with a function with "use strict" directive. function foo(a = 1) { } ``` Examples of **correct** code for this rule with the `"function"` option: ``` /\*eslint strict: ["error", "function"]\*/ function foo() { "use strict"; } (function() { "use strict"; function bar() { } function baz(a = 1) { } }()); var foo = (function() { "use strict"; return function foo(a = 1) { }; }()); ``` ### never Examples of **incorrect** code for this rule with the `"never"` option: ``` /\*eslint strict: ["error", "never"]\*/ "use strict"; function foo() { } ``` ``` /\*eslint strict: ["error", "never"]\*/ function foo() { "use strict"; } ``` Examples of **correct** code for this rule with the `"never"` option: ``` /\*eslint strict: ["error", "never"]\*/ function foo() { } ``` ### earlier default (removed) (removed) The default option (that is, no string option specified) for this rule was **removed** in ESLint v1.0. The `"function"` option is most similar to the removed option. This option ensures that all functions are executed in strict mode. A strict mode directive must be present in global code or in every top-level function declaration or expression. It does not concern itself with unnecessary strict mode directives in nested functions that are already strict, nor with multiple strict mode directives at the same level. Examples of **incorrect** code for this rule with the earlier default option which has been removed: ``` // "strict": "error" function foo() { } ``` ``` // "strict": "error" (function() { function bar() { "use strict"; } }()); ``` Examples of **correct** code for this rule with the earlier default option which has been removed: ``` // "strict": "error" "use strict"; function foo() { } ``` ``` // "strict": "error" function foo() { "use strict"; } ``` ``` // "strict": "error" (function() { "use strict"; function bar() { "use strict"; } }()); ``` When Not To Use It ------------------ In a codebase that has both strict and non-strict code, either turn this rule off, or [selectively disable it](strict../user-guide/configuring/rules#disabling-rules) where necessary. For example, functions referencing `arguments.callee` are invalid in strict mode. A [full list of strict mode differences](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode/Transitioning_to_strict_mode#Differences_from_non-strict_to_strict) is available on MDN. Version ------- This rule was introduced in ESLint v0.1.0. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/strict.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/strict.js)
programming_docs
eslint no-dupe-keys no-dupe-keys ============ Disallow duplicate keys in object literals ✅ Recommended The `"extends": "eslint:recommended"` property in a [configuration file](no-dupe-keys../user-guide/configuring/configuration-files#extending-configuration-files) enables this rule Multiple properties with the same key in object literals can cause unexpected behavior in your application. ``` var foo = { bar: "baz", bar: "qux" }; ``` Rule Details ------------ This rule disallows duplicate keys in object literals. Examples of **incorrect** code for this rule: ``` /\*eslint no-dupe-keys: "error"\*/ var foo = { bar: "baz", bar: "qux" }; var foo = { "bar": "baz", bar: "qux" }; var foo = { 0x1: "baz", 1: "qux" }; ``` Examples of **correct** code for this rule: ``` /\*eslint no-dupe-keys: "error"\*/ var foo = { bar: "baz", quxx: "qux" }; ``` Version ------- This rule was introduced in ESLint v0.0.9. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/no-dupe-keys.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/no-dupe-keys.js) eslint radix radix ===== Enforce the consistent use of the radix argument when using `parseInt()` 💡 hasSuggestions Some problems reported by this rule are manually fixable by editor [suggestions](radix../developer-guide/working-with-rules#providing-suggestions) When using the `parseInt()` function it is common to omit the second argument, the radix, and let the function try to determine from the first argument what type of number it is. By default, `parseInt()` will autodetect decimal and hexadecimal (via `0x` prefix). Prior to ECMAScript 5, `parseInt()` also autodetected octal literals, which caused problems because many developers assumed a leading `0` would be ignored. This confusion led to the suggestion that you always use the radix parameter to `parseInt()` to eliminate unintended consequences. So instead of doing this: ``` var num = parseInt("071"); // 57 ``` Do this: ``` var num = parseInt("071", 10); // 71 ``` ECMAScript 5 changed the behavior of `parseInt()` so that it no longer autodetects octal literals and instead treats them as decimal literals. However, the differences between hexadecimal and decimal interpretation of the first parameter causes many developers to continue using the radix parameter to ensure the string is interpreted in the intended way. On the other hand, if the code is targeting only ES5-compliant environments passing the radix `10` may be redundant. In such a case you might want to disallow using such a radix. Rule Details ------------ This rule is aimed at preventing the unintended conversion of a string to a number of a different base than intended or at preventing the redundant `10` radix if targeting modern environments only. Options ------- There are two options for this rule: * `"always"` enforces providing a radix (default) * `"as-needed"` disallows providing the `10` radix ### always Examples of **incorrect** code for the default `"always"` option: ``` /\*eslint radix: "error"\*/ var num = parseInt("071"); var num = parseInt(someValue); var num = parseInt("071", "abc"); var num = parseInt("071", 37); var num = parseInt(); ``` Examples of **correct** code for the default `"always"` option: ``` /\*eslint radix: "error"\*/ var num = parseInt("071", 10); var num = parseInt("071", 8); var num = parseFloat(someValue); ``` ### as-needed Examples of **incorrect** code for the `"as-needed"` option: ``` /\*eslint radix: ["error", "as-needed"]\*/ var num = parseInt("071", 10); var num = parseInt("071", "abc"); var num = parseInt(); ``` Examples of **correct** code for the `"as-needed"` option: ``` /\*eslint radix: ["error", "as-needed"]\*/ var num = parseInt("071"); var num = parseInt("071", 8); var num = parseFloat(someValue); ``` When Not To Use It ------------------ If you don’t want to enforce either presence or omission of the `10` radix value you can turn this rule off. Version ------- This rule was introduced in ESLint v0.0.7. Further Reading --------------- [parseInt Radix](https://davidwalsh.name/parseint-radix) Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/radix.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/radix.js) eslint no-trailing-spaces no-trailing-spaces ================== Disallow trailing whitespace at the end of lines 🔧 Fixable Some problems reported by this rule are automatically fixable by the `--fix` [command line](no-trailing-spaces../user-guide/command-line-interface#--fix) option Sometimes in the course of editing files, you can end up with extra whitespace at the end of lines. These whitespace differences can be picked up by source control systems and flagged as diffs, causing frustration for developers. While this extra whitespace causes no functional issues, many code conventions require that trailing spaces be removed before check-in. Rule Details ------------ This rule disallows trailing whitespace (spaces, tabs, and other Unicode whitespace characters) at the end of lines. Examples of **incorrect** code for this rule: ``` /\*eslint no-trailing-spaces: "error"\*/ var foo = 0;//••••• var baz = 5;//•• //••••• ``` Examples of **correct** code for this rule: ``` /\*eslint no-trailing-spaces: "error"\*/ var foo = 0; var baz = 5; ``` Options ------- This rule has an object option: * `"skipBlankLines": false` (default) disallows trailing whitespace on empty lines * `"skipBlankLines": true` allows trailing whitespace on empty lines * `"ignoreComments": false` (default) disallows trailing whitespace in comment blocks * `"ignoreComments": true` allows trailing whitespace in comment blocks ### skipBlankLines Examples of **correct** code for this rule with the `{ "skipBlankLines": true }` option: ``` /\*eslint no-trailing-spaces: ["error", { "skipBlankLines": true }]\*/ var foo = 0; var baz = 5; //••••• ``` ### ignoreComments Examples of **correct** code for this rule with the `{ "ignoreComments": true }` option: ``` /\*eslint no-trailing-spaces: ["error", { "ignoreComments": true }]\*/ //foo• //••••• /\*\* \*•baz \*•• \*•bar \*/ ``` Version ------- This rule was introduced in ESLint v0.7.1. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/no-trailing-spaces.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/no-trailing-spaces.js) eslint no-useless-computed-key no-useless-computed-key ======================= Disallow unnecessary computed property keys in objects and classes 🔧 Fixable Some problems reported by this rule are automatically fixable by the `--fix` [command line](no-useless-computed-key../user-guide/command-line-interface#--fix) option It’s unnecessary to use computed properties with literals such as: ``` var foo = {["a"]: "b"}; ``` The code can be rewritten as: ``` var foo = {"a": "b"}; ``` Rule Details ------------ This rule disallows unnecessary usage of computed property keys. Examples of **incorrect** code for this rule: ``` /\*eslint no-useless-computed-key: "error"\*/ var a = { ['0']: 0 }; var a = { ['0+1,234']: 0 }; var a = { [0]: 0 }; var a = { ['x']: 0 }; var a = { ['x']() {} }; ``` Examples of **correct** code for this rule: ``` /\*eslint no-useless-computed-key: "error"\*/ var c = { 'a': 0 }; var c = { 0: 0 }; var a = { x() {} }; var c = { a: 0 }; var c = { '0+1,234': 0 }; ``` Examples of additional **correct** code for this rule: ``` /\*eslint no-useless-computed-key: "error"\*/ var c = { "\_\_proto\_\_": foo, // defines object's prototype ["\_\_proto\_\_"]: bar // defines a property named "\_\_proto\_\_" }; ``` Options ------- This rule has an object option: * `enforceForClassMembers` set to `true` additionally applies this rule to class members (Default `false`). ### enforceForClassMembers By default, this rule does not check class declarations and class expressions, as the default value for `enforceForClassMembers` is `false`. When `enforceForClassMembers` is set to `true`, the rule will also disallow unnecessary computed keys inside of class fields, class methods, class getters, and class setters. Examples of **incorrect** code for this rule with the `{ "enforceForClassMembers": true }` option: ``` /\*eslint no-useless-computed-key: ["error", { "enforceForClassMembers": true }]\*/ class Foo { ["foo"] = "bar"; [0]() {} ['a']() {} get ['b']() {} set ['c'](value) {} static ["foo"] = "bar"; static ['a']() {} } ``` Examples of **correct** code for this rule with the `{ "enforceForClassMembers": true }` option: ``` /\*eslint no-useless-computed-key: ["error", { "enforceForClassMembers": true }]\*/ class Foo { "foo" = "bar"; 0() {} 'a'() {} get 'b'() {} set 'c'(value) {} static "foo" = "bar"; static 'a'() {} } ``` Examples of additional **correct** code for this rule with the `{ "enforceForClassMembers": true }` option: ``` /\*eslint no-useless-computed-key: ["error", { "enforceForClassMembers": true }]\*/ class Foo { ["constructor"]; // instance field named "constructor" "constructor"() {} // the constructor of this class ["constructor"]() {} // method named "constructor" static ["constructor"]; // static field named "constructor" static ["prototype"]; // runtime error, it would be a parsing error without `[]` } ``` When Not To Use It ------------------ If you don’t want to be notified about unnecessary computed property keys, you can safely disable this rule. Version ------- This rule was introduced in ESLint v2.9.0. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/no-useless-computed-key.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/no-useless-computed-key.js) eslint quotes quotes ====== Enforce the consistent use of either backticks, double, or single quotes 🔧 Fixable Some problems reported by this rule are automatically fixable by the `--fix` [command line](quotes../user-guide/command-line-interface#--fix) option JavaScript allows you to define strings in one of three ways: double quotes, single quotes, and backticks (as of ECMAScript 6). For example: ``` /\*eslint-env es6\*/ var double = "double"; var single = 'single'; var backtick = `backtick`; // ES6 only ``` Each of these lines creates a string and, in some cases, can be used interchangeably. The choice of how to define strings in a codebase is a stylistic one outside of template literals (which allow embedded of expressions to be interpreted). Many codebases require strings to be defined in a consistent manner. Rule Details ------------ This rule enforces the consistent use of either backticks, double, or single quotes. Options ------- This rule has two options, a string option and an object option. String option: * `"double"` (default) requires the use of double quotes wherever possible * `"single"` requires the use of single quotes wherever possible * `"backtick"` requires the use of backticks wherever possible Object option: * `"avoidEscape": true` allows strings to use single-quotes or double-quotes so long as the string contains a quote that would have to be escaped otherwise * `"allowTemplateLiterals": true` allows strings to use backticks **Deprecated**: The object property `avoid-escape` is deprecated; please use the object property `avoidEscape` instead. ### double Examples of **incorrect** code for this rule with the default `"double"` option: ``` /\*eslint quotes: ["error", "double"]\*/ var single = 'single'; var unescaped = 'a string containing "double" quotes'; var backtick = `back\ntick`; // you can use \n in single or double quoted strings ``` Examples of **correct** code for this rule with the default `"double"` option: ``` /\*eslint quotes: ["error", "double"]\*/ /\*eslint-env es6\*/ var double = "double"; var backtick = `back tick`; // backticks are allowed due to newline var backtick = tag`backtick`; // backticks are allowed due to tag ``` ### single Examples of **incorrect** code for this rule with the `"single"` option: ``` /\*eslint quotes: ["error", "single"]\*/ var double = "double"; var unescaped = "a string containing 'single' quotes"; ``` Examples of **correct** code for this rule with the `"single"` option: ``` /\*eslint quotes: ["error", "single"]\*/ /\*eslint-env es6\*/ var single = 'single'; var backtick = `back${x}tick`; // backticks are allowed due to substitution ``` ### backticks Examples of **incorrect** code for this rule with the `"backtick"` option: ``` /\*eslint quotes: ["error", "backtick"]\*/ var single = 'single'; var double = "double"; var unescaped = 'a string containing `backticks`'; ``` Examples of **correct** code for this rule with the `"backtick"` option: ``` /\*eslint quotes: ["error", "backtick"]\*/ /\*eslint-env es6\*/ var backtick = `backtick`; ``` ### avoidEscape Examples of additional **correct** code for this rule with the `"double", { "avoidEscape": true }` options: ``` /\*eslint quotes: ["error", "double", { "avoidEscape": true }]\*/ var single = 'a string containing "double" quotes'; ``` Examples of additional **correct** code for this rule with the `"single", { "avoidEscape": true }` options: ``` /\*eslint quotes: ["error", "single", { "avoidEscape": true }]\*/ var double = "a string containing 'single' quotes"; ``` Examples of additional **correct** code for this rule with the `"backtick", { "avoidEscape": true }` options: ``` /\*eslint quotes: ["error", "backtick", { "avoidEscape": true }]\*/ var double = "a string containing `backtick` quotes" ``` ### allowTemplateLiterals Examples of additional **correct** code for this rule with the `"double", { "allowTemplateLiterals": true }` options: ``` /\*eslint quotes: ["error", "double", { "allowTemplateLiterals": true }]\*/ var double = "double"; var double = `double`; ``` Examples of additional **correct** code for this rule with the `"single", { "allowTemplateLiterals": true }` options: ``` /\*eslint quotes: ["error", "single", { "allowTemplateLiterals": true }]\*/ var single = 'single'; var single = `single`; ``` `{ "allowTemplateLiterals": false }` will not disallow the usage of all template literals. If you want to forbid any instance of template literals, use [no-restricted-syntax](quotesno-restricted-syntax) and target the `TemplateLiteral` selector. When Not To Use It ------------------ If you do not need consistency in your string styles, you can safely disable this rule. Version ------- This rule was introduced in ESLint v0.0.7. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/quotes.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/quotes.js) eslint no-unreachable-loop no-unreachable-loop =================== Disallow loops with a body that allows only one iteration A loop that can never reach the second iteration is a possible error in the code. ``` for (let i = 0; i < arr.length; i++) { if (arr[i].name === myName) { doSomething(arr[i]); // break was supposed to be here } break; } ``` In rare cases where only one iteration (or at most one iteration) is intended behavior, the code should be refactored to use `if` conditionals instead of `while`, `do-while` and `for` loops. It’s considered a best practice to avoid using loop constructs for such cases. Rule Details ------------ This rule aims to detect and disallow loops that can have at most one iteration, by performing static code path analysis on loop bodies. In particular, this rule will disallow a loop with a body that exits the loop in all code paths. If all code paths in the loop’s body will end with either a `break`, `return` or a `throw` statement, the second iteration of such loop is certainly unreachable, regardless of the loop’s condition. This rule checks `while`, `do-while`, `for`, `for-in` and `for-of` loops. You can optionally disable checks for each of these constructs. Examples of **incorrect** code for this rule: ``` /\*eslint no-unreachable-loop: "error"\*/ while (foo) { doSomething(foo); foo = foo.parent; break; } function verifyList(head) { let item = head; do { if (verify(item)) { return true; } else { return false; } } while (item); } function findSomething(arr) { for (var i = 0; i < arr.length; i++) { if (isSomething(arr[i])) { return arr[i]; } else { throw new Error("Doesn't exist."); } } } for (key in obj) { if (key.startsWith("\_")) { break; } firstKey = key; firstValue = obj[key]; break; } for (foo of bar) { if (foo.id === id) { doSomething(foo); } break; } ``` Examples of **correct** code for this rule: ``` /\*eslint no-unreachable-loop: "error"\*/ while (foo) { doSomething(foo); foo = foo.parent; } function verifyList(head) { let item = head; do { if (verify(item)) { item = item.next; } else { return false; } } while (item); return true; } function findSomething(arr) { for (var i = 0; i < arr.length; i++) { if (isSomething(arr[i])) { return arr[i]; } } throw new Error("Doesn't exist."); } for (key in obj) { if (key.startsWith("\_")) { continue; } firstKey = key; firstValue = obj[key]; break; } for (foo of bar) { if (foo.id === id) { doSomething(foo); break; } } ``` Please note that this rule is not designed to check loop conditions, and will not warn in cases such as the following examples. Examples of additional **correct** code for this rule: ``` /\*eslint no-unreachable-loop: "error"\*/ do { doSomething(); } while (false) for (let i = 0; i < 1; i++) { doSomething(i); } for (const a of [1]) { doSomething(a); } ``` Options ------- This rule has an object option, with one option: * `"ignore"` - an optional array of loop types that will be ignored by this rule. ### ignore You can specify up to 5 different elements in the `"ignore"` array: * `"WhileStatement"` - to ignore all `while` loops. * `"DoWhileStatement"` - to ignore all `do-while` loops. * `"ForStatement"` - to ignore all `for` loops (does not apply to `for-in` and `for-of` loops). * `"ForInStatement"` - to ignore all `for-in` loops. * `"ForOfStatement"` - to ignore all `for-of` loops. Examples of **correct** code for this rule with the `"ignore"` option: ``` /\*eslint no-unreachable-loop: ["error", { "ignore": ["ForInStatement", "ForOfStatement"] }]\*/ for (var key in obj) { hasEnumerableProperties = true; break; } for (const a of b) break; ``` Known Limitations ----------------- Static code path analysis, in general, does not evaluate conditions. Due to this fact, this rule might miss reporting cases such as the following: ``` for (let i = 0; i < 10; i++) { doSomething(i); if (true) { break; } } ``` Related Rules ------------- * <no-unreachable> * <no-constant-condition> * <no-unmodified-loop-condition> * <for-direction> Version ------- This rule was introduced in ESLint v7.3.0. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/no-unreachable-loop.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/no-unreachable-loop.js)
programming_docs
eslint no-control-regex no-control-regex ================ Disallow control characters in regular expressions ✅ Recommended The `"extends": "eslint:recommended"` property in a [configuration file](no-control-regex../user-guide/configuring/configuration-files#extending-configuration-files) enables this rule Control characters are special, invisible characters in the ASCII range 0-31. These characters are rarely used in JavaScript strings so a regular expression containing elements that explicitly match these characters is most likely a mistake. Rule Details ------------ This rule disallows control characters and some escape sequences that match control characters in regular expressions. The following elements of regular expression patterns are considered possible errors in typing and are therefore disallowed by this rule: * Hexadecimal character escapes from `\x00` to `\x1F`. * Unicode character escapes from `\u0000` to `\u001F`. * Unicode code point escapes from `\u{0}` to `\u{1F}`. * Unescaped raw characters from U+0000 to U+001F. Control escapes such as `\t` and `\n` are allowed by this rule. Examples of **incorrect** code for this rule: ``` /\*eslint no-control-regex: "error"\*/ var pattern1 = /\x00/; var pattern2 = /\x0C/; var pattern3 = /\x1F/; var pattern4 = /\u000C/; var pattern5 = /\u{C}/u; var pattern6 = new RegExp("\x0C"); // raw U+000C character in the pattern var pattern7 = new RegExp("\\x0C"); // \x0C pattern ``` Examples of **correct** code for this rule: ``` /\*eslint no-control-regex: "error"\*/ var pattern1 = /\x20/; var pattern2 = /\u0020/; var pattern3 = /\u{20}/u; var pattern4 = /\t/; var pattern5 = /\n/; var pattern6 = new RegExp("\x20"); var pattern7 = new RegExp("\\t"); var pattern8 = new RegExp("\\n"); ``` Known Limitations ----------------- When checking `RegExp` constructor calls, this rule examines evaluated regular expression patterns. Therefore, although this rule intends to allow syntax such as `\t`, it doesn’t allow `new RegExp("\t")` since the evaluated pattern (string value of `"\t"`) contains a raw control character (the TAB character). ``` /\*eslint no-control-regex: "error"\*/ new RegExp("\t"); // disallowed since the pattern is: <TAB> new RegExp("\\t"); // allowed since the pattern is: \t ``` There is no difference in behavior between `new RegExp("\t")` and `new RegExp("\\t")`, and the intention to match the TAB character is clear in both cases. They are equally valid for the purpose of this rule, but it only allows `new RegExp("\\t")`. When Not To Use It ------------------ If you need to use control character pattern matching, then you should turn this rule off. Related Rules ------------- * <no-div-regex> * <no-regex-spaces> Version ------- This rule was introduced in ESLint v0.1.0. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/no-control-regex.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/no-control-regex.js) eslint no-func-assign no-func-assign ============== Disallow reassigning `function` declarations ✅ Recommended The `"extends": "eslint:recommended"` property in a [configuration file](no-func-assign../user-guide/configuring/configuration-files#extending-configuration-files) enables this rule JavaScript functions can be written as a FunctionDeclaration `function foo() { ... }` or as a FunctionExpression `var foo = function() { ... };`. While a JavaScript interpreter might tolerate it, overwriting/reassigning a function written as a FunctionDeclaration is often indicative of a mistake or issue. ``` function foo() {} foo = bar; ``` Rule Details ------------ This rule disallows reassigning `function` declarations. Examples of **incorrect** code for this rule: ``` /\*eslint no-func-assign: "error"\*/ function foo() {} foo = bar; function foo() { foo = bar; } var a = function hello() { hello = 123; }; ``` Examples of **incorrect** code for this rule, unlike the corresponding rule in JSHint: ``` /\*eslint no-func-assign: "error"\*/ foo = bar; function foo() {} ``` Examples of **correct** code for this rule: ``` /\*eslint no-func-assign: "error"\*/ var foo = function () {} foo = bar; function foo(foo) { // `foo` is shadowed. foo = bar; } function foo() { var foo = bar; // `foo` is shadowed. } ``` Version ------- This rule was introduced in ESLint v0.0.9. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/no-func-assign.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/no-func-assign.js) eslint no-console no-console ========== Disallow the use of `console` In JavaScript that is designed to be executed in the browser, it’s considered a best practice to avoid using methods on `console`. Such messages are considered to be for debugging purposes and therefore not suitable to ship to the client. In general, calls using `console` should be stripped before being pushed to production. ``` console.log("Made it here."); console.error("That shouldn't have happened."); ``` Rule Details ------------ This rule disallows calls or assignments to methods of the `console` object. Examples of **incorrect** code for this rule: ``` /\* eslint no-console: "error" \*/ console.log("Log a debug level message."); console.warn("Log a warn level message."); console.error("Log an error level message."); console.log = foo(); ``` Examples of **correct** code for this rule: ``` /\* eslint no-console: "error" \*/ // custom console Console.log("Hello world!"); ``` Options ------- This rule has an object option for exceptions: * `"allow"` has an array of strings which are allowed methods of the `console` object Examples of additional **correct** code for this rule with a sample `{ "allow": ["warn", "error"] }` option: ``` /\* eslint no-console: ["error", { allow: ["warn", "error"] }] \*/ console.warn("Log a warn level message."); console.error("Log an error level message."); ``` When Not To Use It ------------------ If you’re using Node.js, however, `console` is used to output information to the user and so is not strictly used for debugging purposes. If you are developing for Node.js then you most likely do not want this rule enabled. Another case where you might not use this rule is if you want to enforce console calls and not console overwrites. For example: ``` /\* eslint no-console: ["error", { allow: ["warn"] }] \*/ console.error = function (message) { throw new Error(message); }; ``` With the `no-console` rule in the above example, ESLint will report an error. For the above example, you can disable the rule: ``` // eslint-disable-next-line no-console console.error = function (message) { throw new Error(message); }; // or console.error = function (message) { // eslint-disable-line no-console throw new Error(message); }; ``` However, you might not want to manually add `eslint-disable-next-line` or `eslint-disable-line`. You can achieve the effect of only receiving errors for console calls with the `no-restricted-syntax` rule: ``` { "rules": { "no-console": "off", "no-restricted-syntax": [ "error", { "selector": "CallExpression[callee.object.name='console'][callee.property.name!=/^(log|warn|error|info|trace)$/]", "message": "Unexpected property on console object was called" } ] } } ``` Related Rules ------------- * <no-alert> * <no-debugger> Version ------- This rule was introduced in ESLint v0.0.2. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/no-console.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/no-console.js) eslint prefer-template prefer-template =============== Require template literals instead of string concatenation 🔧 Fixable Some problems reported by this rule are automatically fixable by the `--fix` [command line](prefer-template../user-guide/command-line-interface#--fix) option In ES2015 (ES6), we can use template literals instead of string concatenation. ``` var str = "Hello, " + name + "!"; ``` ``` /\*eslint-env es6\*/ var str = `Hello, ${name}!`; ``` Rule Details ------------ This rule is aimed to flag usage of `+` operators with strings. Examples -------- Examples of **incorrect** code for this rule: ``` /\*eslint prefer-template: "error"\*/ var str = "Hello, " + name + "!"; var str = "Time: " + (12 \* 60 \* 60 \* 1000); ``` Examples of **correct** code for this rule: ``` /\*eslint prefer-template: "error"\*/ /\*eslint-env es6\*/ var str = "Hello World!"; var str = `Hello, ${name}!`; var str = `Time: ${12 \* 60 \* 60 \* 1000}`; // This is reported by `no-useless-concat`. var str = "Hello, " + "World!"; ``` When Not To Use It ------------------ This rule should not be used in ES3/5 environments. In ES2015 (ES6) or later, if you don’t want to be notified about string concatenation, you can safely disable this rule. Related Rules ------------- * <no-useless-concat> * <quotes> Version ------- This rule was introduced in ESLint v1.2.0. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/prefer-template.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/prefer-template.js) eslint spaced-line-comment spaced-line-comment =================== Enforces consistent spacing after `//` in line comments. (removed) This rule was **removed** in ESLint v1.0 and **replaced** by the [spaced-comment](spaced-line-commentspaced-comment) rule. Some style guides require or disallow a whitespace immediately after the initial `//` of a line comment. Whitespace after the `//` makes it easier to read text in comments. On the other hand, commenting out code is easier without having to put a whitespace right after the `//`. Rule Details ------------ This rule will enforce consistency of spacing after the start of a line comment `//`. This rule takes two arguments. If the first is `"always"` then the `//` must be followed by at least once whitespace. If `"never"` then there should be no whitespace following. The default is `"always"`. The second argument is an object with one key, `"exceptions"`. The value is an array of string patterns which are considered exceptions to the rule. It is important to note that the exceptions are ignored if the first argument is `"never"`. Exceptions cannot be mixed. Examples of **incorrect** code for this rule: ``` // When ["never"] // This is a comment with a whitespace at the beginning ``` ``` //When ["always"] //This is a comment with no whitespace at the beginning var foo = 5; ``` ``` // When ["always",{"exceptions":["-","+"]}] //------++++++++ // Comment block //------++++++++ ``` Examples of **correct** code for this rule: ``` // When ["always"] // This is a comment with a whitespace at the beginning var foo = 5; ``` ``` //When ["never"] //This is a comment with no whitespace at the beginning var foo = 5; ``` ``` // When ["always",{"exceptions":["-"]}] //-------------- // Comment block //-------------- ``` ``` // When ["always",{"exceptions":["-+"]}] //-+-+-+-+-+-+-+ // Comment block //-+-+-+-+-+-+-+ ``` Related Rules ------------- * <spaced-comment> Version ------- This rule was introduced in ESLint v0.9.0 and removed in v1.0.0-rc-1. eslint multiline-comment-style multiline-comment-style ======================= Enforce a particular style for multiline comments 🔧 Fixable Some problems reported by this rule are automatically fixable by the `--fix` [command line](multiline-comment-style../user-guide/command-line-interface#--fix) option Many style guides require a particular style for comments that span multiple lines. For example, some style guides prefer the use of a single block comment for multiline comments, whereas other style guides prefer consecutive line comments. Rule Details ------------ This rule aims to enforce a particular style for multiline comments. ### Options This rule has a string option, which can have one of the following values: * `"starred-block"` (default): Disallows consecutive line comments in favor of block comments. Additionally, requires block comments to have an aligned `*` character before each line. * `"bare-block"`: Disallows consecutive line comments in favor of block comments, and disallows block comments from having a `"*"` character before each line. * `"separate-lines"`: Disallows block comments in favor of consecutive line comments The rule always ignores directive comments such as `/* eslint-disable */`. Additionally, unless the mode is `"starred-block"`, the rule ignores JSDoc comments. Examples of **incorrect** code for this rule with the default `"starred-block"` option: ``` /\* eslint multiline-comment-style: ["error", "starred-block"] \*/ // this line // calls foo() foo(); /\* this line calls foo() \*/ foo(); /\* this comment \* is missing a newline after /\* \*/ /\* \* this comment \* is missing a newline at the end \*/ /\* \* the star in this line should have a space before it \*/ /\* \* the star on the following line should have a space before it \*/ ``` Examples of **correct** code for this rule with the default `"starred-block"` option: ``` /\* eslint multiline-comment-style: ["error", "starred-block"] \*/ /\* \* this line \* calls foo() \*/ foo(); // single-line comment ``` Examples of **incorrect** code for this rule with the `"bare-block"` option: ``` /\* eslint multiline-comment-style: ["error", "bare-block"] \*/ // this line // calls foo() foo(); /\* \* this line \* calls foo() \*/ foo(); ``` Examples of **correct** code for this rule with the `"bare-block"` option: ``` /\* eslint multiline-comment-style: ["error", "bare-block"] \*/ /\* this line calls foo() \*/ foo(); ``` Examples of **incorrect** code for this rule with the `"separate-lines"` option: ``` /\* eslint multiline-comment-style: ["error", "separate-lines"] \*/ /\* This line calls foo() \*/ foo(); /\* \* This line \* calls foo() \*/ foo(); ``` Examples of **correct** code for this rule with the `"separate-lines"` option: ``` /\* eslint multiline-comment-style: ["error", "separate-lines"] \*/ // This line // calls foo() foo(); ``` When Not To Use It ------------------ If you don’t want to enforce a particular style for multiline comments, you can disable the rule. Version ------- This rule was introduced in ESLint v4.10.0. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/multiline-comment-style.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/multiline-comment-style.js) eslint function-call-argument-newline function-call-argument-newline ============================== Enforce line breaks between arguments of a function call 🔧 Fixable Some problems reported by this rule are automatically fixable by the `--fix` [command line](function-call-argument-newline../user-guide/command-line-interface#--fix) option A number of style guides require or disallow line breaks between arguments of a function call. Rule Details ------------ This rule enforces line breaks between arguments of a function call. Options ------- This rule has a string option: * `"always"` (default) requires line breaks between arguments * `"never"` disallows line breaks between arguments * `"consistent"` requires consistent usage of line breaks between arguments ### always Examples of **incorrect** code for this rule with the default `"always"` option: ``` /\*eslint function-call-argument-newline: ["error", "always"]\*/ foo("one", "two", "three"); bar("one", "two", { one: 1, two: 2 }); baz("one", "two", (x) => { console.log(x); }); ``` Examples of **correct** code for this rule with the default `"always"` option: ``` /\*eslint function-call-argument-newline: ["error", "always"]\*/ foo( "one", "two", "three" ); bar( "one", "two", { one: 1, two: 2 } ); // or bar( "one", "two", { one: 1, two: 2 } ); baz( "one", "two", (x) => { console.log(x); } ); ``` ### never Examples of **incorrect** code for this rule with the `"never"` option: ``` /\*eslint function-call-argument-newline: ["error", "never"]\*/ foo( "one", "two", "three" ); bar( "one", "two", { one: 1, two: 2 } ); baz( "one", "two", (x) => { console.log(x); } ); ``` Examples of **correct** code for this rule with the `"never"` option: ``` /\*eslint function-call-argument-newline: ["error", "never"]\*/ foo("one", "two", "three"); // or foo( "one", "two", "three" ); bar("one", "two", { one: 1, two: 2 }); // or bar("one", "two", { one: 1, two: 2 }); baz("one", "two", (x) => { console.log(x); }); ``` ### consistent Examples of **incorrect** code for this rule with the `"consistent"` option: ``` /\*eslint function-call-argument-newline: ["error", "consistent"]\*/ foo("one", "two", "three"); //or foo("one", "two", "three"); bar("one", "two", { one: 1, two: 2} ); baz("one", "two", (x) => { console.log(x); } ); ``` Examples of **correct** code for this rule with the `"consistent"` option: ``` /\*eslint function-call-argument-newline: ["error", "consistent"]\*/ foo("one", "two", "three"); // or foo( "one", "two", "three" ); bar("one", "two", { one: 1, two: 2 }); // or bar( "one", "two", { one: 1, two: 2 } ); // or bar( "one", "two", { one: 1, two: 2 } ); baz("one", "two", (x) => { console.log(x); }); // or baz( "one", "two", (x) => { console.log(x); } ); ``` When Not To Use It ------------------ If you don’t want to enforce line breaks between arguments, don’t enable this rule. Related Rules ------------- * <function-paren-newline> * <func-call-spacing> * <object-property-newline> * <array-element-newline> Version ------- This rule was introduced in ESLint v6.2.0. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/function-call-argument-newline.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/function-call-argument-newline.js) eslint prefer-promise-reject-errors prefer-promise-reject-errors ============================ Require using Error objects as Promise rejection reasons It is considered good practice to only pass instances of the built-in `Error` object to the `reject()` function for user-defined errors in Promises. `Error` objects automatically store a stack trace, which can be used to debug an error by determining where it came from. If a Promise is rejected with a non-`Error` value, it can be difficult to determine where the rejection occurred. Rule Details ------------ This rule aims to ensure that Promises are only rejected with `Error` objects. Options ------- This rule takes one optional object argument: * `allowEmptyReject: true` (`false` by default) allows calls to `Promise.reject()` with no arguments. Examples of **incorrect** code for this rule: ``` /\*eslint prefer-promise-reject-errors: "error"\*/ Promise.reject("something bad happened"); Promise.reject(5); Promise.reject(); new Promise(function(resolve, reject) { reject("something bad happened"); }); new Promise(function(resolve, reject) { reject(); }); ``` Examples of **correct** code for this rule: ``` /\*eslint prefer-promise-reject-errors: "error"\*/ Promise.reject(new Error("something bad happened")); Promise.reject(new TypeError("something bad happened")); new Promise(function(resolve, reject) { reject(new Error("something bad happened")); }); var foo = getUnknownValue(); Promise.reject(foo); ``` Examples of **correct** code for this rule with the `allowEmptyReject: true` option: ``` /\*eslint prefer-promise-reject-errors: ["error", {"allowEmptyReject": true}]\*/ Promise.reject(); new Promise(function(resolve, reject) { reject(); }); ``` Known Limitations ----------------- Due to the limits of static analysis, this rule cannot guarantee that you will only reject Promises with `Error` objects. While the rule will report cases where it can guarantee that the rejection reason is clearly not an `Error`, it will not report cases where there is uncertainty about whether a given reason is an `Error`. For more information on this caveat, see the [similar limitations](prefer-promise-reject-errorsno-throw-literal#known-limitations) in the `no-throw-literal` rule. To avoid conflicts between rules, this rule does not report non-error values used in `throw` statements in async functions, even though these lead to Promise rejections. To lint for these cases, use the [`no-throw-literal`](prefer-promise-reject-errorsno-throw-literal) rule. When Not To Use It ------------------ If you’re using custom non-error values as Promise rejection reasons, you can turn off this rule. Related Rules ------------- * <no-throw-literal> Version ------- This rule was introduced in ESLint v3.14.0. Further Reading --------------- [Warning Explanations | bluebird](http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-rejected-with-a-non-error) Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/prefer-promise-reject-errors.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/prefer-promise-reject-errors.js)
programming_docs
eslint no-void no-void ======= Disallow `void` operators The `void` operator takes an operand and returns `undefined`: `void expression` will evaluate `expression` and return `undefined`. It can be used to ignore any side effects `expression` may produce: The common case of using `void` operator is to get a “pure” `undefined` value as prior to ES5 the `undefined` variable was mutable: ``` // will always return undefined (function(){ return void 0; })(); // will return 1 in ES3 and undefined in ES5+ (function(){ undefined = 1; return undefined; })(); // will throw TypeError in ES5+ (function(){ 'use strict'; undefined = 1; })(); ``` Another common case is to minify code as `void 0` is shorter than `undefined`: ``` foo = void 0; foo = undefined; ``` When used with IIFE (immediately-invoked function expression), `void` can be used to force the function keyword to be treated as an expression instead of a declaration: ``` var foo = 1; void function(){ foo = 1; }() // will assign foo a value of 1 +function(){ foo = 1; }() // same as above ``` ``` function(){ foo = 1; }() // will throw SyntaxError ``` Some code styles prohibit `void` operator, marking it as non-obvious and hard to read. Rule Details ------------ This rule aims to eliminate use of void operator. Examples of **incorrect** code for this rule: ``` /\*eslint no-void: "error"\*/ void foo void someFunction(); var foo = void bar(); function baz() { return void 0; } ``` Options ------- This rule has an object option: * `allowAsStatement` set to `true` allows the void operator to be used as a statement (Default `false`). ### allowAsStatement When `allowAsStatement` is set to true, the rule will not error on cases that the void operator is used as a statement, i.e. when it’s not used in an expression position, like in a variable assignment or a function return. Examples of **incorrect** code for `{ "allowAsStatement": true }`: ``` /\*eslint no-void: ["error", { "allowAsStatement": true }]\*/ var foo = void bar(); function baz() { return void 0; } ``` Examples of **correct** code for `{ "allowAsStatement": true }`: ``` /\*eslint no-void: ["error", { "allowAsStatement": true }]\*/ void foo; void someFunction(); ``` When Not To Use It ------------------ If you intentionally use the `void` operator then you can disable this rule. Related Rules ------------- * <no-undef-init> * <no-undefined> Version ------- This rule was introduced in ESLint v0.8.0. Further Reading --------------- [void operator - JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/void) [O’Reilly Media - Technology and Business Training](https://oreilly.com/javascript/excerpts/javascript-good-parts/bad-parts.html) Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/no-void.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/no-void.js) eslint space-in-parens space-in-parens =============== Enforce consistent spacing inside parentheses 🔧 Fixable Some problems reported by this rule are automatically fixable by the `--fix` [command line](space-in-parens../user-guide/command-line-interface#--fix) option Some style guides require or disallow spaces inside of parentheses: ``` foo( 'bar' ); var x = ( 1 + 2 ) \* 3; foo('bar'); var x = (1 + 2) \* 3; ``` Rule Details ------------ This rule will enforce consistent spacing directly inside of parentheses, by disallowing or requiring one or more spaces to the right of `(` and to the left of `)`. As long as you do not explicitly disallow empty parentheses using the `"empty"` exception , `()` will be allowed. Options ------- There are two options for this rule: * `"never"` (default) enforces zero spaces inside of parentheses * `"always"` enforces a space inside of parentheses Depending on your coding conventions, you can choose either option by specifying it in your configuration: ``` "space-in-parens": ["error", "always"] ``` ### “never” Examples of **incorrect** code for this rule with the default `"never"` option: ``` /\*eslint space-in-parens: ["error", "never"]\*/ foo( ); foo( 'bar'); foo('bar' ); foo( 'bar' ); foo( /\* bar \*/ ); var foo = ( 1 + 2 ) \* 3; ( function () { return 'bar'; }() ); ``` Examples of **correct** code for this rule with the default `"never"` option: ``` /\*eslint space-in-parens: ["error", "never"]\*/ foo(); foo('bar'); foo(/\* bar \*/); var foo = (1 + 2) \* 3; (function () { return 'bar'; }()); ``` ### “always” Examples of **incorrect** code for this rule with the `"always"` option: ``` /\*eslint space-in-parens: ["error", "always"]\*/ foo( 'bar'); foo('bar' ); foo('bar'); foo(/\* bar \*/); var foo = (1 + 2) \* 3; (function () { return 'bar'; }()); ``` Examples of **correct** code for this rule with the `"always"` option: ``` /\*eslint space-in-parens: ["error", "always"]\*/ foo(); foo( ); foo( 'bar' ); foo( /\* bar \*/ ); var foo = ( 1 + 2 ) \* 3; ( function () { return 'bar'; }() ); ``` ### Exceptions An object literal may be used as a third array item to specify exceptions, with the key `"exceptions"` and an array as the value. These exceptions work in the context of the first option. That is, if `"always"` is set to enforce spacing, then any “exception” will *disallow* spacing. Conversely, if `"never"` is set to disallow spacing, then any “exception” will *enforce* spacing. Note that this rule only enforces spacing within parentheses; it does not check spacing within curly or square brackets, but will enforce or disallow spacing of those brackets if and only if they are adjacent to an opening or closing parenthesis. The following exceptions are available: `["{}", "[]", "()", "empty"]`. ### Empty Exception Empty parens exception and behavior: * `always` allows for both `()` and `( )` * `never` (default) requires `()` * `always` excepting `empty` requires `()` * `never` excepting `empty` requires `( )` (empty parens without a space is here forbidden) ### Examples Examples of **incorrect** code for this rule with the `"never", { "exceptions": ["{}"] }` option: ``` /\*eslint space-in-parens: ["error", "never", { "exceptions": ["{}"] }]\*/ foo({bar: 'baz'}); foo(1, {bar: 'baz'}); ``` Examples of **correct** code for this rule with the `"never", { "exceptions": ["{}"] }` option: ``` /\*eslint space-in-parens: ["error", "never", { "exceptions": ["{}"] }]\*/ foo( {bar: 'baz'} ); foo(1, {bar: 'baz'} ); ``` Examples of **incorrect** code for this rule with the `"always", { "exceptions": ["{}"] }` option: ``` /\*eslint space-in-parens: ["error", "always", { "exceptions": ["{}"] }]\*/ foo( {bar: 'baz'} ); foo( 1, {bar: 'baz'} ); ``` Examples of **correct** code for this rule with the `"always", { "exceptions": ["{}"] }` option: ``` /\*eslint space-in-parens: ["error", "always", { "exceptions": ["{}"] }]\*/ foo({bar: 'baz'}); foo( 1, {bar: 'baz'}); ``` Examples of **incorrect** code for this rule with the `"never", { "exceptions": ["[]"] }` option: ``` /\*eslint space-in-parens: ["error", "never", { "exceptions": ["[]"] }]\*/ foo([bar, baz]); foo([bar, baz], 1); ``` Examples of **correct** code for this rule with the `"never", { "exceptions": ["[]"] }` option: ``` /\*eslint space-in-parens: ["error", "never", { "exceptions": ["[]"] }]\*/ foo( [bar, baz] ); foo( [bar, baz], 1); ``` Examples of **incorrect** code for this rule with the `"always", { "exceptions": ["[]"] }` option: ``` /\*eslint space-in-parens: ["error", "always", { "exceptions": ["[]"] }]\*/ foo( [bar, baz] ); foo( [bar, baz], 1 ); ``` Examples of **correct** code for this rule with the `"always", { "exceptions": ["[]"] }` option: ``` /\*eslint space-in-parens: ["error", "always", { "exceptions": ["[]"] }]\*/ foo([bar, baz]); foo([bar, baz], 1 ); ``` Examples of **incorrect** code for this rule with the `"never", { "exceptions": ["()"] }]` option: ``` /\*eslint space-in-parens: ["error", "never", { "exceptions": ["()"] }]\*/ foo((1 + 2)); foo((1 + 2), 1); foo(bar()); ``` Examples of **correct** code for this rule with the `"never", { "exceptions": ["()"] }]` option: ``` /\*eslint space-in-parens: ["error", "never", { "exceptions": ["()"] }]\*/ foo( (1 + 2) ); foo( (1 + 2), 1); foo(bar() ); ``` Examples of **incorrect** code for this rule with the `"always", { "exceptions": ["()"] }]` option: ``` /\*eslint space-in-parens: ["error", "always", { "exceptions": ["()"] }]\*/ foo( ( 1 + 2 ) ); foo( ( 1 + 2 ), 1 ); ``` Examples of **correct** code for this rule with the `"always", { "exceptions": ["()"] }]` option: ``` /\*eslint space-in-parens: ["error", "always", { "exceptions": ["()"] }]\*/ foo(( 1 + 2 )); foo(( 1 + 2 ), 1 ); ``` The `"empty"` exception concerns empty parentheses, and works the same way as the other exceptions, inverting the first option. Example of **incorrect** code for this rule with the `"never", { "exceptions": ["empty"] }]` option: ``` /\*eslint space-in-parens: ["error", "never", { "exceptions": ["empty"] }]\*/ foo(); ``` Example of **correct** code for this rule with the `"never", { "exceptions": ["empty"] }]` option: ``` /\*eslint space-in-parens: ["error", "never", { "exceptions": ["empty"] }]\*/ foo( ); ``` Example of **incorrect** code for this rule with the `"always", { "exceptions": ["empty"] }]` option: ``` /\*eslint space-in-parens: ["error", "always", { "exceptions": ["empty"] }]\*/ foo( ); ``` Example of **correct** code for this rule with the `"always", { "exceptions": ["empty"] }]` option: ``` /\*eslint space-in-parens: ["error", "always", { "exceptions": ["empty"] }]\*/ foo(); ``` You can include multiple entries in the `"exceptions"` array. Examples of **incorrect** code for this rule with the `"always", { "exceptions": ["{}", "[]"] }]` option: ``` /\*eslint space-in-parens: ["error", "always", { "exceptions": ["{}", "[]"] }]\*/ bar( {bar:'baz'} ); baz( 1, [1,2] ); foo( {bar: 'baz'}, [1, 2] ); ``` Examples of **correct** code for this rule with the `"always", { "exceptions": ["{}", "[]"] }]` option: ``` /\*eslint space-in-parens: ["error", "always", { "exceptions": ["{}", "[]"] }]\*/ bar({bar:'baz'}); baz( 1, [1,2]); foo({bar: 'baz'}, [1, 2]); ``` When Not To Use It ------------------ You can turn this rule off if you are not concerned with the consistency of spacing between parentheses. Related Rules ------------- * <array-bracket-spacing> * <object-curly-spacing> * <computed-property-spacing> Version ------- This rule was introduced in ESLint v0.8.0. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/space-in-parens.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/space-in-parens.js) eslint array-element-newline array-element-newline ===================== Enforce line breaks after each array element 🔧 Fixable Some problems reported by this rule are automatically fixable by the `--fix` [command line](array-element-newline../user-guide/command-line-interface#--fix) option A number of style guides require or disallow line breaks between array elements. Rule Details ------------ This rule enforces line breaks between array elements. Options ------- This rule has either a string option: * `"always"` (default) requires line breaks between array elements * `"never"` disallows line breaks between array elements * `"consistent"` requires consistent usage of linebreaks between array elements Or an object option (Requires line breaks if any of properties is satisfied. Otherwise, disallows line breaks): * `"multiline": <boolean>` requires line breaks if there are line breaks inside elements. If this is false, this condition is disabled. * `"minItems": <number>` requires line breaks if the number of elements is at least the given integer. If this is 0, this condition will act the same as the option `"always"`. If this is `null` (the default), this condition is disabled. Alternatively, different configurations can be specified for array expressions and array patterns: ``` { "array-element-newline": ["error", { "ArrayExpression": "consistent", "ArrayPattern": { "minItems": 3 }, }] } ``` * `"ArrayExpression"` configuration for array expressions (if unspecified, this rule will not apply to array expressions) * `"ArrayPattern"` configuration for array patterns of destructuring assignments (if unspecified, this rule will not apply to array patterns) ### always Examples of **incorrect** code for this rule with the default `"always"` option: ``` /\*eslint array-element-newline: ["error", "always"]\*/ var c = [1, 2]; var d = [1, 2, 3]; var e = [1, 2, 3 ]; var f = [ 1, 2, 3 ]; var g = [ function foo() { dosomething(); }, function bar() { dosomething(); } ]; ``` Examples of **correct** code for this rule with the default `"always"` option: ``` /\*eslint array-element-newline: ["error", "always"]\*/ var a = []; var b = [1]; var c = [1, 2]; var d = [1, 2, 3]; var d = [ 1, 2, 3 ]; var e = [ function foo() { dosomething(); }, function bar() { dosomething(); } ]; ``` ### never Examples of **incorrect** code for this rule with the `"never"` option: ``` /\*eslint array-element-newline: ["error", "never"]\*/ var c = [ 1, 2 ]; var d = [ 1, 2, 3 ]; var e = [ function foo() { dosomething(); }, function bar() { dosomething(); } ]; ``` Examples of **correct** code for this rule with the `"never"` option: ``` /\*eslint array-element-newline: ["error", "never"]\*/ var a = []; var b = [1]; var c = [1, 2]; var d = [1, 2, 3]; var e = [ 1, 2, 3]; var f = [ 1, 2, 3 ]; var g = [ function foo() { dosomething(); }, function bar() { dosomething(); } ]; ``` ### consistent Examples of **incorrect** code for this rule with the `"consistent"` option: ``` /\*eslint array-element-newline: ["error", "consistent"]\*/ var a = [ 1, 2, 3 ]; var b = [ function foo() { dosomething(); }, function bar() { dosomething(); }, function baz() { dosomething(); } ]; ``` Examples of **correct** code for this rule with the `"consistent"` option: ``` /\*eslint array-element-newline: ["error", "consistent"]\*/ var a = []; var b = [1]; var c = [1, 2]; var d = [1, 2, 3]; var e = [ 1, 2 ]; var f = [ 1, 2, 3 ]; var g = [ function foo() { dosomething(); }, function bar() { dosomething(); }, function baz() { dosomething(); } ]; var h = [ function foo() { dosomething(); }, function bar() { dosomething(); }, function baz() { dosomething(); } ]; ``` ### multiline Examples of **incorrect** code for this rule with the `{ "multiline": true }` option: ``` /\*eslint array-element-newline: ["error", { "multiline": true }]\*/ var d = [1, 2, 3]; var e = [ function foo() { dosomething(); }, function bar() { dosomething(); } ]; ``` Examples of **correct** code for this rule with the `{ "multiline": true }` option: ``` /\*eslint array-element-newline: ["error", { "multiline": true }]\*/ var a = []; var b = [1]; var c = [1, 2]; var d = [1, 2, 3]; var e = [ function foo() { dosomething(); }, function bar() { dosomething(); } ]; ``` ### minItems Examples of **incorrect** code for this rule with the `{ "minItems": 3 }` option: ``` /\*eslint array-element-newline: ["error", { "minItems": 3 }]\*/ var c = [1, 2]; var d = [1, 2, 3]; var e = [ function foo() { dosomething(); }, function bar() { dosomething(); } ]; ``` Examples of **correct** code for this rule with the `{ "minItems": 3 }` option: ``` /\*eslint array-element-newline: ["error", { "minItems": 3 }]\*/ var a = []; var b = [1]; var c = [1, 2]; var d = [1, 2, 3]; var e = [ function foo() { dosomething(); }, function bar() { dosomething(); } ]; ``` ### multiline and minItems Examples of **incorrect** code for this rule with the `{ "multiline": true, "minItems": 3 }` options: ``` /\*eslint array-element-newline: ["error", { "multiline": true, "minItems": 3 }]\*/ var c = [1, 2]; var d = [1, 2, 3]; var e = [ function foo() { dosomething(); }, function bar() { dosomething(); } ]; ``` Examples of **correct** code for this rule with the `{ "multiline": true, "minItems": 3 }` options: ``` /\*eslint array-element-newline: ["error", { "multiline": true, "minItems": 3 }]\*/ var a = []; var b = [1]; var c = [1, 2]; var d = [1, 2, 3]; var e = [ function foo() { dosomething(); }, function bar() { dosomething(); } ]; ``` ### ArrayExpression and ArrayPattern Examples of **incorrect** code for this rule with the `{ "ArrayExpression": "always", "ArrayPattern": "never" }` options: ``` /\*eslint array-element-newline: ["error", { "ArrayExpression": "always", "ArrayPattern": "never" }]\*/ var a = [1, 2]; var b = [1, 2, 3]; var c = [ function foo() { dosomething(); }, function bar() { dosomething(); } ]; var [d, e] = arr; var [f, g, h] = arr; var [i = function foo() { dosomething() }, j = function bar() { dosomething() }] = arr ``` Examples of **correct** code for this rule with the `{ "ArrayExpression": "always", "ArrayPattern": "never" }` options: ``` /\*eslint array-element-newline: ["error", { "ArrayExpression": "always", "ArrayPattern": "never" }]\*/ var a = [1, 2]; var b = [1, 2, 3]; var c = [ function foo() { dosomething(); }, function bar() { dosomething(); } ]; var [d, e] = arr var [f, g, h] = arr var [i = function foo() { dosomething() }, j = function bar() { dosomething() }] = arr ``` When Not To Use It ------------------ If you don’t want to enforce linebreaks between array elements, don’t enable this rule. Compatibility ------------- * **JSCS:** [validateNewlineAfterArrayElements](https://jscs-dev.github.io/rule/validateNewlineAfterArrayElements) Related Rules ------------- * <array-bracket-spacing> * <array-bracket-newline> * <object-property-newline> * <object-curly-spacing> * <object-curly-newline> * <max-statements-per-line> * <block-spacing> * <brace-style> Version ------- This rule was introduced in ESLint v4.0.0-rc.0. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/array-element-newline.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/array-element-newline.js) eslint init-declarations init-declarations ================= Require or disallow initialization in variable declarations In JavaScript, variables can be assigned during declaration, or at any point afterwards using an assignment statement. For example, in the following code, `foo` is initialized during declaration, while `bar` is initialized later. ``` var foo = 1; var bar; if (foo) { bar = 1; } else { bar = 2; } ``` Rule Details ------------ This rule is aimed at enforcing or eliminating variable initializations during declaration. For example, in the following code, `foo` is initialized during declaration, while `bar` is not. ``` var foo = 1; var bar; bar = 2; ``` This rule aims to bring consistency to variable initializations and declarations. Options ------- The rule takes two options: 1. A string which must be either `"always"` (the default), to enforce initialization at declaration, or `"never"` to disallow initialization during declaration. This rule applies to `var`, `let`, and `const` variables, however `"never"` is ignored for `const` variables, as unassigned `const`s generate a parse error. 2. An object that further controls the behavior of this rule. Currently, the only available parameter is `ignoreForLoopInit`, which indicates if initialization at declaration is allowed in `for` loops when `"never"` is set, since it is a very typical use case. You can configure the rule as follows: Variables must be initialized at declaration (default) ``` { "init-declarations": ["error", "always"], } ``` Variables must not be initialized at declaration ``` { "init-declarations": ["error", "never"] } ``` Variables must not be initialized at declaration, except in for loops, where it is allowed ``` { "init-declarations": ["error", "never", { "ignoreForLoopInit": true }] } ``` ### always Examples of **incorrect** code for the default `"always"` option: ``` /\*eslint init-declarations: ["error", "always"]\*/ /\*eslint-env es6\*/ function foo() { var bar; let baz; } ``` Examples of **correct** code for the default `"always"` option: ``` /\*eslint init-declarations: ["error", "always"]\*/ /\*eslint-env es6\*/ function foo() { var bar = 1; let baz = 2; const qux = 3; } ``` ### never Examples of **incorrect** code for the `"never"` option: ``` /\*eslint init-declarations: ["error", "never"]\*/ /\*eslint-env es6\*/ function foo() { var bar = 1; let baz = 2; for (var i = 0; i < 1; i++) {} } ``` Examples of **correct** code for the `"never"` option: ``` /\*eslint init-declarations: ["error", "never"]\*/ /\*eslint-env es6\*/ function foo() { var bar; let baz; const buzz = 1; } ``` The `"never"` option ignores `const` variable initializations. ### ignoreForLoopInit Examples of **correct** code for the `"never", { "ignoreForLoopInit": true }` options: ``` /\*eslint init-declarations: ["error", "never", { "ignoreForLoopInit": true }]\*/ for (var i = 0; i < 1; i++) {} ``` When Not To Use It ------------------ When you are indifferent as to how your variables are initialized. Version ------- This rule was introduced in ESLint v1.0.0-rc-1. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/init-declarations.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/init-declarations.js)
programming_docs
eslint no-multiple-empty-lines no-multiple-empty-lines ======================= Disallow multiple empty lines 🔧 Fixable Some problems reported by this rule are automatically fixable by the `--fix` [command line](no-multiple-empty-lines../user-guide/command-line-interface#--fix) option Some developers prefer to have multiple blank lines removed, while others feel that it helps improve readability. Whitespace is useful for separating logical sections of code, but excess whitespace takes up more of the screen. Rule Details ------------ This rule aims to reduce the scrolling required when reading through your code. It will warn when the maximum amount of empty lines has been exceeded. Options ------- This rule has an object option: * `"max"` (default: `2`) enforces a maximum number of consecutive empty lines. * `"maxEOF"` enforces a maximum number of consecutive empty lines at the end of files. * `"maxBOF"` enforces a maximum number of consecutive empty lines at the beginning of files. ### max Examples of **incorrect** code for this rule with the default `{ "max": 2 }` option: ``` /\*eslint no-multiple-empty-lines: "error"\*/ var foo = 5; var bar = 3; ``` Examples of **correct** code for this rule with the default `{ "max": 2 }` option: ``` /\*eslint no-multiple-empty-lines: "error"\*/ var foo = 5; var bar = 3; ``` ### maxEOF Examples of **incorrect** code for this rule with the `{ max: 2, maxEOF: 0 }` options: ``` /\*eslint no-multiple-empty-lines: ["error", { "max": 2, "maxEOF": 0 }]\*/ var foo = 5; var bar = 3; ``` Examples of **correct** code for this rule with the `{ max: 2, maxEOF: 0 }` options: ``` /\*eslint no-multiple-empty-lines: ["error", { "max": 2, "maxEOF": 0 }]\*/ var foo = 5; var bar = 3; ``` **Note**: Although this ensures zero empty lines at the EOF, most editors will still show one empty line at the end if the file ends with a line break, as illustrated below. There is no empty line at the end of a file after the last `\n`, although editors may show an additional line. A true additional line would be represented by `\n\n`. **Incorrect**: ``` 1 /\*eslint no-multiple-empty-lines: ["error", { "max": 2, "maxEOF": 0 }]\*/⏎ 2 ⏎ 3 var foo = 5;⏎ 4 ⏎ 5 ⏎ 6 var bar = 3;⏎ 7 ⏎ 8 ``` **Correct**: ``` 1 /\*eslint no-multiple-empty-lines: ["error", { "max": 2, "maxEOF": 0 }]\*/⏎ 2 ⏎ 3 var foo = 5;⏎ 4 ⏎ 5 ⏎ 6 var bar = 3;⏎ 7 ``` ### maxBOF Examples of **incorrect** code for this rule with the `{ max: 2, maxBOF: 1 }` options: ``` /\*eslint no-multiple-empty-lines: ["error", { "max": 2, "maxBOF": 1 }]\*/ var foo = 5; var bar = 3; ``` Examples of **correct** code for this rule with the `{ max: 2, maxBOF: 1 }` options: ``` /\*eslint no-multiple-empty-lines: ["error", { "max": 2, "maxBOF": 1}]\*/ var foo = 5; var bar = 3; ``` When Not To Use It ------------------ If you do not care about extra blank lines, turn this off. Version ------- This rule was introduced in ESLint v0.9.0. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/no-multiple-empty-lines.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/no-multiple-empty-lines.js) eslint no-unsafe-optional-chaining no-unsafe-optional-chaining =========================== Disallow use of optional chaining in contexts where the `undefined` value is not allowed ✅ Recommended The `"extends": "eslint:recommended"` property in a [configuration file](no-unsafe-optional-chaining../user-guide/configuring/configuration-files#extending-configuration-files) enables this rule The optional chaining (`?.`) expression can short-circuit with a return value of `undefined`. Therefore, treating an evaluated optional chaining expression as a function, object, number, etc., can cause TypeError or unexpected results. For example: ``` var obj = undefined; 1 in obj?.foo; // TypeError with (obj?.foo); // TypeError for (bar of obj?.foo); // TypeError bar instanceof obj?.foo; // TypeError const { bar } = obj?.foo; // TypeError ``` Also, parentheses limit the scope of short-circuiting in chains. For example: ``` var obj = undefined; (obj?.foo)(); // TypeError (obj?.foo).bar; // TypeError ``` Rule Details ------------ This rule aims to detect some cases where the use of optional chaining doesn’t prevent runtime errors. In particular, it flags optional chaining expressions in positions where short-circuiting to `undefined` causes throwing a TypeError afterward. Examples of **incorrect** code for this rule: ``` /\*eslint no-unsafe-optional-chaining: "error"\*/ (obj?.foo)(); (obj?.foo).bar; (foo?.()).bar; (foo?.()).bar(); (obj?.foo ?? obj?.bar)(); (foo || obj?.foo)(); (obj?.foo && foo)(); (foo ? obj?.foo : bar)(); (foo, obj?.bar).baz; (obj?.foo)`template`; new (obj?.foo)(); [...obj?.foo]; bar(...obj?.foo); 1 in obj?.foo; bar instanceof obj?.foo; for (bar of obj?.foo); const { bar } = obj?.foo; [{ bar } = obj?.foo] = []; with (obj?.foo); class A extends obj?.foo {} var a = class A extends obj?.foo {}; async function foo () { const { bar } = await obj?.foo; (await obj?.foo)(); (await obj?.foo).bar; } ``` Examples of **correct** code for this rule: ``` /\*eslint no-unsafe-optional-chaining: "error"\*/ (obj?.foo)?.(); obj?.foo(); (obj?.foo ?? bar)(); obj?.foo.bar; obj.foo?.bar; foo?.()?.bar; (obj?.foo ?? bar)`template`; new (obj?.foo ?? bar)(); var baz = {...obj?.foo}; const { bar } = obj?.foo || baz; async function foo () { const { bar } = await obj?.foo || baz; (await obj?.foo)?.(); (await obj?.foo)?.bar; } ``` Options ------- This rule has an object option: * `disallowArithmeticOperators`: Disallow arithmetic operations on optional chaining expressions (Default `false`). If this is `true`, this rule warns arithmetic operations on optional chaining expressions, which possibly result in `NaN`. ### disallowArithmeticOperators With this option set to `true` the rule is enforced for: * Unary operators: `-`, `+` * Arithmetic operators: `+`, `-`, `/`, `*`, `%`, `**` * Assignment operators: `+=`, `-=`, `/=`, `*=`, `%=`, `**=` Examples of additional **incorrect** code for this rule with the `{ "disallowArithmeticOperators": true }` option: ``` /\*eslint no-unsafe-optional-chaining: ["error", { "disallowArithmeticOperators": true }]\*/ +obj?.foo; -obj?.foo; obj?.foo + bar; obj?.foo - bar; obj?.foo / bar; obj?.foo \* bar; obj?.foo % bar; obj?.foo \*\* bar; baz += obj?.foo; baz -= obj?.foo; baz /= obj?.foo; baz \*= obj?.foo; baz %= obj?.foo; baz \*\*= obj?.foo; async function foo () { +await obj?.foo; await obj?.foo + bar; baz += await obj?.foo; } ``` Version ------- This rule was introduced in ESLint v7.15.0. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/no-unsafe-optional-chaining.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/no-unsafe-optional-chaining.js) eslint require-yield require-yield ============= Require generator functions to contain `yield` ✅ Recommended The `"extends": "eslint:recommended"` property in a [configuration file](require-yield../user-guide/configuring/configuration-files#extending-configuration-files) enables this rule Rule Details ------------ This rule generates warnings for generator functions that do not have the `yield` keyword. Examples -------- Examples of **incorrect** code for this rule: ``` /\*eslint require-yield: "error"\*/ /\*eslint-env es6\*/ function\* foo() { return 10; } ``` Examples of **correct** code for this rule: ``` /\*eslint require-yield: "error"\*/ /\*eslint-env es6\*/ function\* foo() { yield 5; return 10; } function foo() { return 10; } // This rule does not warn on empty generator functions. function\* foo() { } ``` When Not To Use It ------------------ If you don’t want to notify generator functions that have no `yield` expression, then it’s safe to disable this rule. Related Rules ------------- * <require-await> Version ------- This rule was introduced in ESLint v1.0.0-rc-1. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/require-yield.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/require-yield.js) eslint no-restricted-imports no-restricted-imports ===================== Disallow specified modules when loaded by `import` Imports are an ES6/ES2015 standard for making the functionality of other modules available in your current module. In CommonJS this is implemented through the `require()` call which makes this ESLint rule roughly equivalent to its CommonJS counterpart `no-restricted-modules`. Why would you want to restrict imports? * Some imports might not make sense in a particular environment. For example, Node.js’ `fs` module would not make sense in an environment that didn’t have a file system. * Some modules provide similar or identical functionality, think `lodash` and `underscore`. Your project may have standardized on a module. You want to make sure that the other alternatives are not being used as this would unnecessarily bloat the project and provide a higher maintenance cost of two dependencies when one would suffice. Rule Details ------------ This rule allows you to specify imports that you don’t want to use in your application. It applies to static imports only, not dynamic ones. Options ------- The syntax to specify restricted imports looks like this: ``` "no-restricted-imports": ["error", "import1", "import2"] ``` or like this: ``` "no-restricted-imports": ["error", { "paths": ["import1", "import2"] }] ``` When using the object form, you can also specify an array of gitignore-style patterns: ``` "no-restricted-imports": ["error", { "paths": ["import1", "import2"], "patterns": ["import1/private/\*", "import2/\*", "!import2/good"] }] ``` You may also specify a custom message for any paths you want to restrict as follows: ``` "no-restricted-imports": ["error", { "name": "import-foo", "message": "Please use import-bar instead." }, { "name": "import-baz", "message": "Please use import-quux instead." }] ``` or like this: ``` "no-restricted-imports": ["error", { "paths": [{ "name": "import-foo", "message": "Please use import-bar instead." }, { "name": "import-baz", "message": "Please use import-quux instead." }] }] ``` or like this if you need to restrict only certain imports from a module: ``` "no-restricted-imports": ["error", { "paths": [{ "name": "import-foo", "importNames": ["Bar"], "message": "Please use Bar from /import-bar/baz/ instead." }] }] ``` or like this if you want to apply a custom message to pattern matches: ``` "no-restricted-imports": ["error", { "patterns": [{ "group": ["import1/private/\*"], "message": "usage of import1 private modules not allowed." }, { "group": ["import2/\*", "!import2/good"], "message": "import2 is deprecated, except the modules in import2/good." }] }] ``` The custom message will be appended to the default error message. Pattern matches can also be configured to be case-sensitive: ``` "no-restricted-imports": ["error", { "patterns": [{ "group": ["import1/private/prefix[A-Z]\*"], "caseSensitive": true }] }] ``` Pattern matches can restrict specific import names only, similar to the `paths` option: ``` "no-restricted-imports": ["error", { "patterns": [{ "group": ["utils/\*"], "importNames": ["isEmpty"], "message": "Use 'isEmpty' from lodash instead." }] }] ``` To restrict the use of all Node.js core imports (via <https://github.com/nodejs/node/tree/master/lib>): ``` "no-restricted-imports": ["error", "assert","buffer","child\_process","cluster","crypto","dgram","dns","domain","events","freelist","fs","http","https","module","net","os","path","punycode","querystring","readline","repl","smalloc","stream","string\_decoder","sys","timers","tls","tracing","tty","url","util","vm","zlib" ], ``` Examples -------- Examples of **incorrect** code for this rule: ``` /\*eslint no-restricted-imports: ["error", "fs"]\*/ import fs from 'fs'; ``` ``` /\*eslint no-restricted-imports: ["error", "fs"]\*/ export { fs } from 'fs'; ``` ``` /\*eslint no-restricted-imports: ["error", "fs"]\*/ export \* from 'fs'; ``` ``` /\*eslint no-restricted-imports: ["error", { "paths": ["cluster"] }]\*/ import cluster from 'cluster'; ``` ``` /\*eslint no-restricted-imports: ["error", { "patterns": ["lodash/\*"] }]\*/ import pick from 'lodash/pick'; ``` ``` /\*eslint no-restricted-imports: ["error", { paths: [{ name: "foo", importNames: ["default"], message: "Please use the default import from '/bar/baz/' instead." }]}]\*/ import DisallowedObject from "foo"; ``` ``` /\*eslint no-restricted-imports: ["error", { paths: [{ name: "foo", importNames: ["DisallowedObject"], message: "Please import 'DisallowedObject' from '/bar/baz/' instead." }]}]\*/ import { DisallowedObject } from "foo"; import { DisallowedObject as AllowedObject } from "foo"; import { "DisallowedObject" as AllowedObject } from "foo"; ``` ``` /\*eslint no-restricted-imports: ["error", { paths: [{ name: "foo", importNames: ["DisallowedObject"], message: "Please import 'DisallowedObject' from '/bar/baz/' instead." }]}]\*/ import \* as Foo from "foo"; ``` ``` /\*eslint no-restricted-imports: ["error", { patterns: [{ group: ["lodash/\*"], message: "Please use the default import from 'lodash' instead." }]}]\*/ import pick from 'lodash/pick'; ``` ``` /\*eslint no-restricted-imports: ["error", { patterns: [{ group: ["foo[A-Z]\*"], caseSensitive: true }]}]\*/ import pick from 'fooBar'; ``` ``` /\*eslint no-restricted-imports: ["error", { patterns: [{ group: ["utils/\*"], importNames: ['isEmpty'], message: "Use 'isEmpty' from lodash instead." }]}]\*/ import { isEmpty } from 'utils/collection-utils'; ``` Examples of **correct** code for this rule: ``` /\*eslint no-restricted-imports: ["error", "fs"]\*/ import crypto from 'crypto'; export { foo } from "bar"; ``` ``` /\*eslint no-restricted-imports: ["error", { "paths": ["fs"], "patterns": ["eslint/\*"] }]\*/ import crypto from 'crypto'; import eslint from 'eslint'; export \* from "path"; ``` ``` /\*eslint no-restricted-imports: ["error", { paths: [{ name: "foo", importNames: ["DisallowedObject"] }] }]\*/ import DisallowedObject from "foo" ``` ``` /\*eslint no-restricted-imports: ["error", { paths: [{ name: "foo", importNames: ["DisallowedObject"], message: "Please import 'DisallowedObject' from '/bar/baz/' instead." }]}]\*/ import { AllowedObject as DisallowedObject } from "foo"; ``` ``` /\*eslint no-restricted-imports: ["error", { patterns: [{ group: ["lodash/\*"], message: "Please use the default import from 'lodash' instead." }]}]\*/ import lodash from 'lodash'; ``` ``` /\*eslint no-restricted-imports: ["error", { patterns: [{ group: ["foo[A-Z]\*"], caseSensitive: true }]}]\*/ import pick from 'food'; ``` ``` /\*eslint no-restricted-imports: ["error", { patterns: [{ group: ["utils/\*"], importNames: ['isEmpty'], message: "Use 'isEmpty' from lodash instead." }]}]\*/ import { hasValues } from 'utils/collection-utils'; ``` When Not To Use It ------------------ Don’t use this rule or don’t include a module in the list for this rule if you want to be able to import a module in your project without an ESLint error or warning. Version ------- This rule was introduced in ESLint v2.0.0-alpha-1. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/no-restricted-imports.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/no-restricted-imports.js) eslint no-iterator no-iterator =========== Disallow the use of the `__iterator__` property The `__iterator__` property was a SpiderMonkey extension to JavaScript that could be used to create custom iterators that are compatible with JavaScript’s `for in` and `for each` constructs. However, this property is now obsolete, so it should not be used. Here’s an example of how this used to work: ``` Foo.prototype.\_\_iterator\_\_ = function() { return new FooIterator(this); } ``` You should use ECMAScript 6 iterators and generators instead. Rule Details ------------ This rule is aimed at preventing errors that may arise from using the `__iterator__` property, which is not implemented in several browsers. As such, it will warn whenever it encounters the `__iterator__` property. Examples of **incorrect** code for this rule: ``` /\*eslint no-iterator: "error"\*/ Foo.prototype.\_\_iterator\_\_ = function() { return new FooIterator(this); }; foo.\_\_iterator\_\_ = function () {}; foo["\_\_iterator\_\_"] = function () {}; ``` Examples of **correct** code for this rule: ``` /\*eslint no-iterator: "error"\*/ var __iterator__ = foo; // Not using the `\_\_iterator\_\_` property. ``` Version ------- This rule was introduced in ESLint v0.0.9. Further Reading --------------- [Iterators and generators - JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators) [null](https://kangax.github.io/es5-compat-table/es6/#Iterators) [Deprecated and obsolete features - JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Deprecated_and_obsolete_features#Object_methods) Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/no-iterator.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/no-iterator.js) eslint max-lines max-lines ========= Enforce a maximum number of lines per file Some people consider large files a code smell. Large files tend to do a lot of things and can make it hard following what’s going. While there is not an objective maximum number of lines considered acceptable in a file, most people would agree it should not be in the thousands. Recommendations usually range from 100 to 500 lines. Rule Details ------------ This rule enforces a maximum number of lines per file, in order to aid in maintainability and reduce complexity. Please note that most editors show an additional empty line at the end if the file ends with a line break. This rule does not count that extra line. Options ------- This rule has a number or object option: * `"max"` (default `300`) enforces a maximum number of lines in a file * `"skipBlankLines": true` ignore lines made up purely of whitespace. * `"skipComments": true` ignore lines containing just comments ### max Examples of **incorrect** code for this rule with a max value of `2`: ``` /\*eslint max-lines: ["error", 2]\*/ var a, b, c; ``` ``` /\*eslint max-lines: ["error", 2]\*/ var a, b,c; ``` ``` /\*eslint max-lines: ["error", 2]\*/ // a comment var a, b,c; ``` Examples of **correct** code for this rule with a max value of `2`: ``` /\*eslint max-lines: ["error", 2]\*/ var a, b, c; ``` ``` /\*eslint max-lines: ["error", 2]\*/ var a, b, c; ``` ``` /\*eslint max-lines: ["error", 2]\*/ // a comment var a, b, c; ``` ### skipBlankLines Examples of **incorrect** code for this rule with the `{ "skipBlankLines": true }` option: ``` /\*eslint max-lines: ["error", {"max": 2, "skipBlankLines": true}]\*/ var a, b, c; ``` Examples of **correct** code for this rule with the `{ "skipBlankLines": true }` option: ``` /\*eslint max-lines: ["error", {"max": 2, "skipBlankLines": true}]\*/ var a, b, c; ``` ### skipComments Examples of **incorrect** code for this rule with the `{ "skipComments": true }` option: ``` /\*eslint max-lines: ["error", {"max": 2, "skipComments": true}]\*/ // a comment var a, b, c; ``` Examples of **correct** code for this rule with the `{ "skipComments": true }` option: ``` /\*eslint max-lines: ["error", {"max": 2, "skipComments": true}]\*/ // a comment var a, b, c; ``` When Not To Use It ------------------ You can turn this rule off if you are not concerned with the number of lines in your files. Compatibility ------------- * **JSCS**: [maximumNumberOfLines](https://jscs-dev.github.io/rule/maximumNumberOfLines) Related Rules ------------- * <complexity> * <max-depth> * <max-lines-per-function> * <max-nested-callbacks> * <max-params> * <max-statements> Version ------- This rule was introduced in ESLint v2.12.0. Further Reading --------------- [Software Module size and file size](https://web.archive.org/web/20160725154648/http://www.mind2b.com/component/content/article/24-software-module-size-and-file-size) Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/max-lines.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/max-lines.js)
programming_docs
eslint id-length id-length ========= Enforce minimum and maximum identifier lengths Very short identifier names like `e`, `x`, `_t` or very long ones like `hashGeneratorResultOutputContainerObject` can make code harder to read and potentially less maintainable. To prevent this, one may enforce a minimum and/or maximum identifier length. ``` var x = 5; // too short; difficult to understand its purpose without context ``` Rule Details ------------ This rule enforces a minimum and/or maximum identifier length convention. This rule counts [graphemes](https://unicode.org/reports/tr29/#Default_Grapheme_Cluster_Table) instead of using [`String length`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length). Options ------- Examples of **incorrect** code for this rule with the default options: ``` /\*eslint id-length: "error"\*/ // default is minimum 2-chars ({ "min": 2 }) /\*eslint-env es6\*/ var x = 5; obj.e = document.body; var foo = function (e) { }; try { dangerousStuff(); } catch (e) { // ignore as many do } var myObj = { a: 1 }; (a) => { a \* a }; class x { } class Foo { x() {} } class Foo { #x() {} } class Foo { x = 1 } class Foo { #x = 1 } function foo(...x) { } function foo([x]) { } var [x] = arr; var { prop: [x]} = {}; function foo({x}) { } var { x } = {}; var { prop: a} = {}; ({ prop: obj.x } = {}); ``` Examples of **correct** code for this rule with the default options: ``` /\*eslint id-length: "error"\*/ // default is minimum 2-chars ({ "min": 2 }) /\*eslint-env es6\*/ var num = 5; function \_f() { return 42; } function \_func() { return 42; } obj.el = document.body; var foo = function (evt) { /\* do stuff \*/ }; try { dangerousStuff(); } catch (error) { // ignore as many do } var myObj = { apple: 1 }; (num) => { num \* num }; function foo(num = 0) { } class MyClass { } class Foo { method() {} } class Foo { #method() {} } class Foo { field = 1 } class Foo { #field = 1 } function foo(...args) { } function foo([longName]) { } var { prop } = {}; var { prop: [longName] } = {}; var [longName] = arr; function foo({ prop }) { } function foo({ a: prop }) { } var { prop } = {}; var { a: prop } = {}; ({ prop: obj.longName } = {}); var data = { "x": 1 }; // excused because of quotes data["y"] = 3; // excused because of calculated property access ``` This rule has an object option: * `"min"` (default: 2) enforces a minimum identifier length * `"max"` (default: Infinity) enforces a maximum identifier length * `"properties": always` (default) enforces identifier length convention for property names * `"properties": never` ignores identifier length convention for property names * `"exceptions"` allows an array of specified identifier names * `"exceptionPatterns"` array of strings representing regular expression patterns, allows identifiers that match any of the patterns. ### min Examples of **incorrect** code for this rule with the `{ "min": 4 }` option: ``` /\*eslint id-length: ["error", { "min": 4 }]\*/ /\*eslint-env es6\*/ var val = 5; obj.e = document.body; function foo (e) { }; try { dangerousStuff(); } catch (e) { // ignore as many do } var myObj = { a: 1 }; (val) => { val \* val }; class x { } class Foo { x() {} } function foo(...x) { } var { x } = {}; var { prop: a} = {}; var [x] = arr; var { prop: [x]} = {}; ({ prop: obj.x } = {}); ``` Examples of **correct** code for this rule with the `{ "min": 4 }` option: ``` /\*eslint id-length: ["error", { "min": 4 }]\*/ /\*eslint-env es6\*/ var value = 5; function func() { return 42; } obj.element = document.body; var foobar = function (event) { /\* do stuff \*/ }; try { dangerousStuff(); } catch (error) { // ignore as many do } var myObj = { apple: 1 }; (value) => { value \* value }; function foobar(value = 0) { } class MyClass { } class Foobar { method() {} } function foobar(...args) { } var { prop } = {}; var [longName] = foo; var { a: [prop] } = {}; var { a: longName } = {}; ({ prop: obj.name } = {}); var data = { "x": 1 }; // excused because of quotes data["y"] = 3; // excused because of calculated property access ``` ### max Examples of **incorrect** code for this rule with the `{ "max": 10 }` option: ``` /\*eslint id-length: ["error", { "max": 10 }]\*/ /\*eslint-env es6\*/ var reallyLongVarName = 5; function reallyLongFuncName() { return 42; } obj.reallyLongPropName = document.body; var foo = function (reallyLongArgName) { /\* do stuff \*/ }; try { dangerousStuff(); } catch (reallyLongErrorName) { // ignore as many do } (reallyLongArgName) => { return !reallyLongArgName; }; var [reallyLongFirstElementName] = arr; ``` Examples of **correct** code for this rule with the `{ "max": 10 }` option: ``` /\*eslint id-length: ["error", { "max": 10 }]\*/ /\*eslint-env es6\*/ var varName = 5; function funcName() { return 42; } obj.propName = document.body; var foo = function (arg) { /\* do stuff \*/ }; try { dangerousStuff(); } catch (error) { // ignore as many do } (arg) => { return !arg; }; var [first] = arr; ``` ### properties Examples of **correct** code for this rule with the `{ "properties": "never" }` option: ``` /\*eslint id-length: ["error", { "properties": "never" }]\*/ /\*eslint-env es6\*/ var myObj = { a: 1 }; ({ a: obj.x.y.z } = {}); ({ prop: obj.i } = {}); ``` ### exceptions Examples of additional **correct** code for this rule with the `{ "exceptions": ["x"] }` option: ``` /\*eslint id-length: ["error", { "exceptions": ["x"] }]\*/ /\*eslint-env es6\*/ var x = 5; function x() { return 42; } obj.x = document.body; var foo = function (x) { /\* do stuff \*/ }; try { dangerousStuff(); } catch (x) { // ignore as many do } (x) => { return x \* x; }; var [x] = arr; const { x } = foo; const { a: x } = foo; ``` ### exceptionPatterns Examples of additional **correct** code for this rule with the `{ "exceptionPatterns": ["E|S", "[x-z]"] }` option: ``` /\*eslint id-length: ["error", { "exceptionPatterns": ["E|S", "[x-z]"] }]\*/ /\*eslint-env es6\*/ var E = 5; function S() { return 42; } obj.x = document.body; var foo = function (x) { /\* do stuff \*/ }; try { dangerousStuff(); } catch (x) { // ignore as many do } (y) => {return y \* y}; var [E] = arr; const { y } = foo; const { a: z } = foo; ``` Related Rules ------------- * <max-len> * <new-cap> * <func-names> * <camelcase> Version ------- This rule was introduced in ESLint v1.0.0. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/id-length.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/id-length.js) eslint no-extra-parens no-extra-parens =============== Disallow unnecessary parentheses 🔧 Fixable Some problems reported by this rule are automatically fixable by the `--fix` [command line](no-extra-parens../user-guide/command-line-interface#--fix) option This rule restricts the use of parentheses to only where they are necessary. Rule Details ------------ This rule always ignores extra parentheses around the following: * RegExp literals such as `(/abc/).test(var)` to avoid conflicts with the [wrap-regex](no-extra-parenswrap-regex) rule * immediately-invoked function expressions (also known as IIFEs) such as `var x = (function () {})();` and `var x = (function () {}());` to avoid conflicts with the [wrap-iife](no-extra-parenswrap-iife) rule * arrow function arguments to avoid conflicts with the [arrow-parens](no-extra-parensarrow-parens) rule Options ------- This rule has a string option: * `"all"` (default) disallows unnecessary parentheses around *any* expression * `"functions"` disallows unnecessary parentheses *only* around function expressions This rule has an object option for exceptions to the `"all"` option: * `"conditionalAssign": false` allows extra parentheses around assignments in conditional test expressions * `"returnAssign": false` allows extra parentheses around assignments in `return` statements * `"nestedBinaryExpressions": false` allows extra parentheses in nested binary expressions * `"ignoreJSX": "none|all|multi-line|single-line"` allows extra parentheses around no/all/multi-line/single-line JSX components. Defaults to `none`. * `"enforceForArrowConditionals": false` allows extra parentheses around ternary expressions which are the body of an arrow function * `"enforceForSequenceExpressions": false` allows extra parentheses around sequence expressions * `"enforceForNewInMemberExpressions": false` allows extra parentheses around `new` expressions in member expressions * `"enforceForFunctionPrototypeMethods": false` allows extra parentheses around immediate `.call` and `.apply` method calls on function expressions and around function expressions in the same context. * `"allowParensAfterCommentPattern": "any-string-pattern"` allows extra parentheses preceded by a comment that matches a regular expression. ### all Examples of **incorrect** code for this rule with the default `"all"` option: ``` /\* eslint no-extra-parens: "error" \*/ a = (b \* c); (a \* b) + c; for (a in (b, c)); for (a in (b)); for (a of (b)); typeof (a); (Object.prototype.toString.call()); (function(){} ? a() : b()); class A { [(x)] = 1; } class B { x = (y + z); } ``` Examples of **correct** code for this rule with the default `"all"` option: ``` /\* eslint no-extra-parens: "error" \*/ (0).toString(); ({}.toString.call()); (function(){}) ? a() : b(); (/^a$/).test(x); for (a of (b, c)); for (a of b); for (a in b, c); for (a in b); class A { [x] = 1; } class B { x = y + z; } ``` ### conditionalAssign Examples of **correct** code for this rule with the `"all"` and `{ "conditionalAssign": false }` options: ``` /\* eslint no-extra-parens: ["error", "all", { "conditionalAssign": false }] \*/ while ((foo = bar())) {} if ((foo = bar())) {} do; while ((foo = bar())) for (;(a = b);); ``` ### returnAssign Examples of **correct** code for this rule with the `"all"` and `{ "returnAssign": false }` options: ``` /\* eslint no-extra-parens: ["error", "all", { "returnAssign": false }] \*/ function a(b) { return (b = 1); } function a(b) { return b ? (c = d) : (c = e); } b => (b = 1); b => b ? (c = d) : (c = e); ``` ### nestedBinaryExpressions Examples of **correct** code for this rule with the `"all"` and `{ "nestedBinaryExpressions": false }` options: ``` /\* eslint no-extra-parens: ["error", "all", { "nestedBinaryExpressions": false }] \*/ x = a || (b && c); x = a + (b \* c); x = (a \* b) / c; ``` ### ignoreJSX Examples of **correct** code for this rule with the `all` and `{ "ignoreJSX": "all" }` options: ``` /\* eslint no-extra-parens: ["error", "all", { ignoreJSX: "all" }] \*/ const Component = (<div />) const Component = ( <div prop={true} /> ) ``` Examples of **incorrect** code for this rule with the `all` and `{ "ignoreJSX": "multi-line" }` options: ``` /\* eslint no-extra-parens: ["error", "all", { ignoreJSX: "multi-line" }] \*/ const Component = (<div />) const Component = (<div><p /></div>) ``` Examples of **correct** code for this rule with the `all` and `{ "ignoreJSX": "multi-line" }` options: ``` /\* eslint no-extra-parens: ["error", "all", { ignoreJSX: "multi-line" }] \*/ const Component = ( <div> <p /> </div> ) const Component = ( <div prop={true} /> ) ``` Examples of **incorrect** code for this rule with the `all` and `{ "ignoreJSX": "single-line" }` options: ``` /\* eslint no-extra-parens: ["error", "all", { ignoreJSX: "single-line" }] \*/ const Component = ( <div> <p /> </div> ) const Component = ( <div prop={true} /> ) ``` Examples of **correct** code for this rule with the `all` and `{ "ignoreJSX": "single-line" }` options: ``` /\* eslint no-extra-parens: ["error", "all", { ignoreJSX: "single-line" }] \*/ const Component = (<div />) const Component = (<div><p /></div>) ``` ### enforceForArrowConditionals Examples of **correct** code for this rule with the `"all"` and `{ "enforceForArrowConditionals": false }` options: ``` /\* eslint no-extra-parens: ["error", "all", { "enforceForArrowConditionals": false }] \*/ const b = a => 1 ? 2 : 3; const d = c => (1 ? 2 : 3); ``` ### enforceForSequenceExpressions Examples of **correct** code for this rule with the `"all"` and `{ "enforceForSequenceExpressions": false }` options: ``` /\* eslint no-extra-parens: ["error", "all", { "enforceForSequenceExpressions": false }] \*/ (a, b); if ((val = foo(), val < 10)) {} while ((val = foo(), val < 10)); ``` ### enforceForNewInMemberExpressions Examples of **correct** code for this rule with the `"all"` and `{ "enforceForNewInMemberExpressions": false }` options: ``` /\* eslint no-extra-parens: ["error", "all", { "enforceForNewInMemberExpressions": false }] \*/ const foo = (new Bar()).baz; const quux = (new Bar())[baz]; (new Bar()).doSomething(); ``` ### enforceForFunctionPrototypeMethods Examples of **correct** code for this rule with the `"all"` and `{ "enforceForFunctionPrototypeMethods": false }` options: ``` /\* eslint no-extra-parens: ["error", "all", { "enforceForFunctionPrototypeMethods": false }] \*/ const foo = (function () {}).call(); const bar = (function () {}).apply(); const baz = (function () {}.call()); const quux = (function () {}.apply()); ``` ### allowParensAfterCommentPattern To make this rule allow extra parentheses preceded by specific comments, set this option to a string pattern that will be passed to the [`RegExp` constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/RegExp). Examples of **correct** code for this rule with the `"all"` and `{ "allowParensAfterCommentPattern": "@type" }` options: ``` /\* eslint no-extra-parens: ["error", "all", { "allowParensAfterCommentPattern": "@type" }] \*/ const span = /\*\*@type {HTMLSpanElement}\*/(event.currentTarget); if (/\*\* @type {Foo | Bar} \*/(options).baz) console.log('Lint free'); foo(/\*\* @type {Bar} \*/ (bar), options, { name: "name", path: "path", }); if (foo) { /\*\* @type {Bar} \*/ (bar).prop = false; } ``` ### functions Examples of **incorrect** code for this rule with the `"functions"` option: ``` /\* eslint no-extra-parens: ["error", "functions"] \*/ ((function foo() {}))(); var y = (function () {return 1;}); ``` Examples of **correct** code for this rule with the `"functions"` option: ``` /\* eslint no-extra-parens: ["error", "functions"] \*/ (0).toString(); (Object.prototype.toString.call()); ({}.toString.call()); (function(){} ? a() : b()); (/^a$/).test(x); a = (b \* c); (a \* b) + c; typeof (a); ``` Related Rules ------------- * <arrow-parens> * <no-cond-assign> * <no-return-assign> Version ------- This rule was introduced in ESLint v0.1.4. Further Reading --------------- [Operator precedence - JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence) Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/no-extra-parens.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/no-extra-parens.js) eslint no-duplicate-imports no-duplicate-imports ==================== Disallow duplicate module imports Using a single `import` statement per module will make the code clearer because you can see everything being imported from that module on one line. In the following example the `module` import on line 1 is repeated on line 3. These can be combined to make the list of imports more succinct. ``` import { merge } from 'module'; import something from 'another-module'; import { find } from 'module'; ``` Rule Details ------------ This rule requires that all imports from a single module that can be merged exist in a single `import` statement. Example of **incorrect** code for this rule: ``` /\*eslint no-duplicate-imports: "error"\*/ import { merge } from 'module'; import something from 'another-module'; import { find } from 'module'; ``` Example of **correct** code for this rule: ``` /\*eslint no-duplicate-imports: "error"\*/ import { merge, find } from 'module'; import something from 'another-module'; ``` Example of **correct** code for this rule: ``` /\*eslint no-duplicate-imports: "error"\*/ // not mergeable import { merge } from 'module'; import \* as something from 'module'; ``` Options ------- This rule takes one optional argument, an object with a single key, `includeExports` which is a `boolean`. It defaults to `false`. If re-exporting from an imported module, you should add the imports to the `import`-statement, and export that directly, not use `export ... from`. Example of **incorrect** code for this rule with the `{ "includeExports": true }` option: ``` /\*eslint no-duplicate-imports: ["error", { "includeExports": true }]\*/ import { merge } from 'module'; export { find } from 'module'; ``` Example of **correct** code for this rule with the `{ "includeExports": true }` option: ``` /\*eslint no-duplicate-imports: ["error", { "includeExports": true }]\*/ import { merge, find } from 'module'; export { find }; ``` Example of **correct** code for this rule with the `{ "includeExports": true }` option: ``` /\*eslint no-duplicate-imports: ["error", { "includeExports": true }]\*/ import { merge, find } from 'module'; // cannot be merged with the above import export \* as something from 'module'; // cannot be written differently export \* from 'module'; ``` Version ------- This rule was introduced in ESLint v2.5.0. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/no-duplicate-imports.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/no-duplicate-imports.js) eslint object-shorthand object-shorthand ================ Require or disallow method and property shorthand syntax for object literals 🔧 Fixable Some problems reported by this rule are automatically fixable by the `--fix` [command line](object-shorthand../user-guide/command-line-interface#--fix) option ECMAScript 6 provides a concise form for defining object literal methods and properties. This syntax can make defining complex object literals much cleaner. Here are a few common examples using the ES5 syntax: ``` // properties var foo = { x: x, y: y, z: z, }; // methods var foo = { a: function() {}, b: function() {} }; ``` Now here are ES6 equivalents: ``` /\*eslint-env es6\*/ // properties var foo = {x, y, z}; // methods var foo = { a() {}, b() {} }; ``` Rule Details ------------ This rule enforces the use of the shorthand syntax. This applies to all methods (including generators) defined in object literals and any properties defined where the key name matches name of the assigned variable. Each of the following properties would warn: ``` /\*eslint object-shorthand: "error"\*/ /\*eslint-env es6\*/ var foo = { w: function() {}, x: function \*() {}, [y]: function() {}, z: z }; ``` In that case the expected syntax would have been: ``` /\*eslint object-shorthand: "error"\*/ /\*eslint-env es6\*/ var foo = { w() {}, \*x() {}, [y]() {}, z }; ``` This rule does not flag arrow functions inside of object literals. The following will *not* warn: ``` /\*eslint object-shorthand: "error"\*/ /\*eslint-env es6\*/ var foo = { x: (y) => y }; ``` Options ------- The rule takes an option which specifies when it should be applied. It can be set to one of the following values: * `"always"` (default) expects that the shorthand will be used whenever possible. * `"methods"` ensures the method shorthand is used (also applies to generators). * `"properties"` ensures the property shorthand is used (where the key and variable name match). * `"never"` ensures that no property or method shorthand is used in any object literal. * `"consistent"` ensures that either all shorthand or all long-form will be used in an object literal. * `"consistent-as-needed"` ensures that either all shorthand or all long-form will be used in an object literal, but ensures all shorthand whenever possible. You can set the option in configuration like this: ``` { "object-shorthand": ["error", "always"] } ``` Additionally, the rule takes an optional object configuration: * `"avoidQuotes": true` indicates that long-form syntax is preferred whenever the object key is a string literal (default: `false`). Note that this option can only be enabled when the string option is set to `"always"`, `"methods"`, or `"properties"`. * `"ignoreConstructors": true` can be used to prevent the rule from reporting errors for constructor functions. (By default, the rule treats constructors the same way as other functions.) Note that this option can only be enabled when the string option is set to `"always"` or `"methods"`. * `"methodsIgnorePattern"` (`string`) for methods whose names match this regex pattern, the method shorthand will not be enforced. Note that this option can only be used when the string option is set to `"always"` or `"methods"`. * `"avoidExplicitReturnArrows": true` indicates that methods are preferred over explicit-return arrow functions for function properties. (By default, the rule allows either of these.) Note that this option can only be enabled when the string option is set to `"always"` or `"methods"`. ### `avoidQuotes` ``` { "object-shorthand": ["error", "always", { "avoidQuotes": true }] } ``` Example of **incorrect** code for this rule with the `"always", { "avoidQuotes": true }` option: ``` /\*eslint object-shorthand: ["error", "always", { "avoidQuotes": true }]\*/ /\*eslint-env es6\*/ var foo = { "bar-baz"() {} }; ``` Example of **correct** code for this rule with the `"always", { "avoidQuotes": true }` option: ``` /\*eslint object-shorthand: ["error", "always", { "avoidQuotes": true }]\*/ /\*eslint-env es6\*/ var foo = { "bar-baz": function() {}, "qux": qux }; ``` ### `ignoreConstructors` ``` { "object-shorthand": ["error", "always", { "ignoreConstructors": true }] } ``` Example of **correct** code for this rule with the `"always", { "ignoreConstructors": true }` option: ``` /\*eslint object-shorthand: ["error", "always", { "ignoreConstructors": true }]\*/ /\*eslint-env es6\*/ var foo = { ConstructorFunction: function() {} }; ``` ### `methodsIgnorePattern` Example of **correct** code for this rule with the `"always", { "methodsIgnorePattern": "^bar$" }` option: ``` /\*eslint object-shorthand: ["error", "always", { "methodsIgnorePattern": "^bar$" }]\*/ var foo = { bar: function() {} }; ``` ### `avoidExplicitReturnArrows` ``` { "object-shorthand": ["error", "always", { "avoidExplicitReturnArrows": true }] } ``` Example of **incorrect** code for this rule with the `"always", { "avoidExplicitReturnArrows": true }` option: ``` /\*eslint object-shorthand: ["error", "always", { "avoidExplicitReturnArrows": true }]\*/ /\*eslint-env es6\*/ var foo = { foo: (bar, baz) => { return bar + baz; }, qux: (foobar) => { return foobar \* 2; } }; ``` Example of **correct** code for this rule with the `"always", { "avoidExplicitReturnArrows": true }` option: ``` /\*eslint object-shorthand: ["error", "always", { "avoidExplicitReturnArrows": true }]\*/ /\*eslint-env es6\*/ var foo = { foo(bar, baz) { return bar + baz; }, qux: foobar => foobar \* 2 }; ``` Example of **incorrect** code for this rule with the `"consistent"` option: ``` /\*eslint object-shorthand: [2, "consistent"]\*/ /\*eslint-env es6\*/ var foo = { a, b: "foo", }; ``` Examples of **correct** code for this rule with the `"consistent"` option: ``` /\*eslint object-shorthand: [2, "consistent"]\*/ /\*eslint-env es6\*/ var foo = { a: a, b: "foo" }; var bar = { a, b, }; ``` Example of **incorrect** code with the `"consistent-as-needed"` option, which is very similar to `"consistent"`: ``` /\*eslint object-shorthand: [2, "consistent-as-needed"]\*/ /\*eslint-env es6\*/ var foo = { a: a, b: b, }; ``` When Not To Use It ------------------ Anyone not yet in an ES6 environment would not want to apply this rule. Others may find the terseness of the shorthand syntax harder to read and may not want to encourage it with this rule. Related Rules ------------- * <no-useless-rename> Version ------- This rule was introduced in ESLint v0.20.0. Further Reading --------------- [Object initializer - JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer) Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/object-shorthand.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/object-shorthand.js)
programming_docs
eslint new-cap new-cap ======= Require constructor names to begin with a capital letter The `new` operator in JavaScript creates a new instance of a particular type of object. That type of object is represented by a constructor function. Since constructor functions are just regular functions, the only defining characteristic is that `new` is being used as part of the call. Native JavaScript functions begin with an uppercase letter to distinguish those functions that are to be used as constructors from functions that are not. Many style guides recommend following this pattern to more easily determine which functions are to be used as constructors. ``` var friend = new Person(); ``` Rule Details ------------ This rule requires constructor names to begin with a capital letter. Certain built-in identifiers are exempt from this rule. These identifiers are: * `Array` * `Boolean` * `Date` * `Error` * `Function` * `Number` * `Object` * `RegExp` * `String` * `Symbol` * `BigInt` Examples of **correct** code for this rule: ``` /\*eslint new-cap: "error"\*/ function foo(arg) { return Boolean(arg); } ``` Options ------- This rule has an object option: * `"newIsCap": true` (default) requires all `new` operators to be called with uppercase-started functions. * `"newIsCap": false` allows `new` operators to be called with lowercase-started or uppercase-started functions. * `"capIsNew": true` (default) requires all uppercase-started functions to be called with `new` operators. * `"capIsNew": false` allows uppercase-started functions to be called without `new` operators. * `"newIsCapExceptions"` allows specified lowercase-started function names to be called with the `new` operator. * `"newIsCapExceptionPattern"` allows any lowercase-started function names that match the specified regex pattern to be called with the `new` operator. * `"capIsNewExceptions"` allows specified uppercase-started function names to be called without the `new` operator. * `"capIsNewExceptionPattern"` allows any uppercase-started function names that match the specified regex pattern to be called without the `new` operator. * `"properties": true` (default) enables checks on object properties * `"properties": false` disables checks on object properties ### newIsCap Examples of **incorrect** code for this rule with the default `{ "newIsCap": true }` option: ``` /\*eslint new-cap: ["error", { "newIsCap": true }]\*/ var friend = new person(); ``` Examples of **correct** code for this rule with the default `{ "newIsCap": true }` option: ``` /\*eslint new-cap: ["error", { "newIsCap": true }]\*/ var friend = new Person(); ``` Examples of **correct** code for this rule with the `{ "newIsCap": false }` option: ``` /\*eslint new-cap: ["error", { "newIsCap": false }]\*/ var friend = new person(); ``` ### capIsNew Examples of **incorrect** code for this rule with the default `{ "capIsNew": true }` option: ``` /\*eslint new-cap: ["error", { "capIsNew": true }]\*/ var colleague = Person(); ``` Examples of **correct** code for this rule with the default `{ "capIsNew": true }` option: ``` /\*eslint new-cap: ["error", { "capIsNew": true }]\*/ var colleague = new Person(); ``` Examples of **correct** code for this rule with the `{ "capIsNew": false }` option: ``` /\*eslint new-cap: ["error", { "capIsNew": false }]\*/ var colleague = Person(); ``` ### newIsCapExceptions Examples of additional **correct** code for this rule with the `{ "newIsCapExceptions": ["events"] }` option: ``` /\*eslint new-cap: ["error", { "newIsCapExceptions": ["events"] }]\*/ var events = require('events'); var emitter = new events(); ``` ### newIsCapExceptionPattern Examples of additional **correct** code for this rule with the `{ "newIsCapExceptionPattern": "^person\\.." }` option: ``` /\*eslint new-cap: ["error", { "newIsCapExceptionPattern": "^person\\.." }]\*/ var friend = new person.acquaintance(); var bestFriend = new person.friend(); ``` Examples of additional **correct** code for this rule with the `{ "newIsCapExceptionPattern": "\\.bar$" }` option: ``` /\*eslint new-cap: ["error", { "newIsCapExceptionPattern": "\\.bar$" }]\*/ var friend = new person.bar(); ``` ### capIsNewExceptions Examples of additional **correct** code for this rule with the `{ "capIsNewExceptions": ["Person"] }` option: ``` /\*eslint new-cap: ["error", { "capIsNewExceptions": ["Person"] }]\*/ function foo(arg) { return Person(arg); } ``` ### capIsNewExceptionPattern Examples of additional **correct** code for this rule with the `{ "capIsNewExceptionPattern": "^person\\.." }` option: ``` /\*eslint new-cap: ["error", { "capIsNewExceptionPattern": "^person\\.." }]\*/ var friend = person.Acquaintance(); var bestFriend = person.Friend(); ``` Examples of additional **correct** code for this rule with the `{ "capIsNewExceptionPattern": "\\.Bar$" }` option: ``` /\*eslint new-cap: ["error", { "capIsNewExceptionPattern": "\\.Bar$" }]\*/ foo.Bar(); ``` Examples of additional **correct** code for this rule with the `{ "capIsNewExceptionPattern": "^Foo" }` option: ``` /\*eslint new-cap: ["error", { "capIsNewExceptionPattern": "^Foo" }]\*/ var x = Foo(42); var y = Foobar(42); var z = Foo.Bar(42); ``` ### properties Examples of **incorrect** code for this rule with the default `{ "properties": true }` option: ``` /\*eslint new-cap: ["error", { "properties": true }]\*/ var friend = new person.acquaintance(); ``` Examples of **correct** code for this rule with the default `{ "properties": true }` option: ``` /\*eslint new-cap: ["error", { "properties": true }]\*/ var friend = new person.Acquaintance(); ``` Examples of **correct** code for this rule with the `{ "properties": false }` option: ``` /\*eslint new-cap: ["error", { "properties": false }]\*/ var friend = new person.acquaintance(); ``` When Not To Use It ------------------ If you have conventions that don’t require an uppercase letter for constructors, or don’t require capitalized functions be only used as constructors, turn this rule off. Version ------- This rule was introduced in ESLint v0.0.3-0. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/new-cap.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/new-cap.js) eslint lines-around-comment lines-around-comment ==================== Require empty lines around comments 🔧 Fixable Some problems reported by this rule are automatically fixable by the `--fix` [command line](lines-around-comment../user-guide/command-line-interface#--fix) option Many style guides require empty lines before or after comments. The primary goal of these rules is to make the comments easier to read and improve readability of the code. Rule Details ------------ This rule requires empty lines before and/or after comments. It can be enabled separately for both block (`/*`) and line (`//`) comments. This rule does not apply to comments that appear on the same line as code and does not require empty lines at the beginning or end of a file. Options ------- This rule has an object option: * `"beforeBlockComment": true` (default) requires an empty line before block comments * `"afterBlockComment": true` requires an empty line after block comments * `"beforeLineComment": true` requires an empty line before line comments * `"afterLineComment": true` requires an empty line after line comments * `"allowBlockStart": true` allows comments to appear at the start of block statements, function bodies, classes, switch statements, and class static blocks * `"allowBlockEnd": true` allows comments to appear at the end of block statements, function bodies, classes, switch statements, and class static blocks * `"allowObjectStart": true` allows comments to appear at the start of object literals * `"allowObjectEnd": true` allows comments to appear at the end of object literals * `"allowArrayStart": true` allows comments to appear at the start of array literals * `"allowArrayEnd": true` allows comments to appear at the end of array literals * `"allowClassStart": true` allows comments to appear at the start of classes * `"allowClassEnd": true` allows comments to appear at the end of classes * `"applyDefaultIgnorePatterns"` enables or disables the default comment patterns to be ignored by the rule * `"ignorePattern"` custom patterns to be ignored by the rule ### beforeBlockComment Examples of **incorrect** code for this rule with the default `{ "beforeBlockComment": true }` option: ``` /\*eslint lines-around-comment: ["error", { "beforeBlockComment": true }]\*/ var night = "long"; /\* what a great and wonderful day \*/ var day = "great" ``` Examples of **correct** code for this rule with the default `{ "beforeBlockComment": true }` option: ``` /\*eslint lines-around-comment: ["error", { "beforeBlockComment": true }]\*/ var night = "long"; /\* what a great and wonderful day \*/ var day = "great" ``` ### afterBlockComment Examples of **incorrect** code for this rule with the `{ "afterBlockComment": true }` option: ``` /\*eslint lines-around-comment: ["error", { "afterBlockComment": true }]\*/ var night = "long"; /\* what a great and wonderful day \*/ var day = "great" ``` Examples of **correct** code for this rule with the `{ "afterBlockComment": true }` option: ``` /\*eslint lines-around-comment: ["error", { "afterBlockComment": true }]\*/ var night = "long"; /\* what a great and wonderful day \*/ var day = "great" ``` ### beforeLineComment Examples of **incorrect** code for this rule with the `{ "beforeLineComment": true }` option: ``` /\*eslint lines-around-comment: ["error", { "beforeLineComment": true }]\*/ var night = "long"; // what a great and wonderful day var day = "great" ``` Examples of **correct** code for this rule with the `{ "beforeLineComment": true }` option: ``` /\*eslint lines-around-comment: ["error", { "beforeLineComment": true }]\*/ var night = "long"; // what a great and wonderful day var day = "great" ``` ### afterLineComment Examples of **incorrect** code for this rule with the `{ "afterLineComment": true }` option: ``` /\*eslint lines-around-comment: ["error", { "afterLineComment": true }]\*/ var night = "long"; // what a great and wonderful day var day = "great" ``` Examples of **correct** code for this rule with the `{ "afterLineComment": true }` option: ``` /\*eslint lines-around-comment: ["error", { "afterLineComment": true }]\*/ var night = "long"; // what a great and wonderful day var day = "great" ``` ### allowBlockStart Examples of **correct** code for this rule with the `{ "beforeLineComment": true, "allowBlockStart": true }` options: ``` /\*eslint lines-around-comment: ["error", { "beforeLineComment": true, "allowBlockStart": true }]\*/ function foo(){ // what a great and wonderful day var day = "great" return day; } if (bar) { // what a great and wonderful day foo(); } class C { // what a great and wonderful day method() { // what a great and wonderful day foo(); } static { // what a great and wonderful day foo(); } } ``` Examples of **correct** code for this rule with the `{ "beforeBlockComment": true, "allowBlockStart": true }` options: ``` /\*eslint lines-around-comment: ["error", { "beforeBlockComment": true, "allowBlockStart": true }]\*/ function foo(){ /\* what a great and wonderful day \*/ var day = "great" return day; } if (bar) { /\* what a great and wonderful day \*/ foo(); } class C { /\* what a great and wonderful day \*/ method() { /\* what a great and wonderful day \*/ foo(); } static { /\* what a great and wonderful day \*/ foo(); } } switch (foo) { /\* what a great and wonderful day \*/ case 1: bar(); break; } ``` ### allowBlockEnd Examples of **correct** code for this rule with the `{ "afterLineComment": true, "allowBlockEnd": true }` option: ``` /\*eslint lines-around-comment: ["error", { "afterLineComment": true, "allowBlockEnd": true }]\*/ function foo(){ var day = "great" return day; // what a great and wonderful day } if (bar) { foo(); // what a great and wonderful day } class C { method() { foo(); // what a great and wonderful day } static { foo(); // what a great and wonderful day } // what a great and wonderful day } ``` Examples of **correct** code for this rule with the `{ "afterBlockComment": true, "allowBlockEnd": true }` option: ``` /\*eslint lines-around-comment: ["error", { "afterBlockComment": true, "allowBlockEnd": true }]\*/ function foo(){ var day = "great" return day; /\* what a great and wonderful day \*/ } if (bar) { foo(); /\* what a great and wonderful day \*/ } class C { method() { foo(); /\* what a great and wonderful day \*/ } static { foo(); /\* what a great and wonderful day \*/ } /\* what a great and wonderful day \*/ } switch (foo) { case 1: bar(); break; /\* what a great and wonderful day \*/ } ``` ### allowClassStart Examples of **incorrect** code for this rule with the `{ "beforeLineComment": true, "allowClassStart": false }` option: ``` /\*eslint lines-around-comment: ["error", { "beforeLineComment": true, "allowClassStart": false }]\*/ class foo { // what a great and wonderful day day() {} }; ``` Examples of **correct** code for this rule with the `{ "beforeLineComment": true, "allowClassStart": false }` option: ``` /\*eslint lines-around-comment: ["error", { "beforeLineComment": true, "allowClassStart": false }]\*/ class foo { // what a great and wonderful day day() {} }; ``` Examples of **correct** code for this rule with the `{ "beforeLineComment": true, "allowClassStart": true }` option: ``` /\*eslint lines-around-comment: ["error", { "beforeLineComment": true, "allowClassStart": true }]\*/ class foo { // what a great and wonderful day day() {} }; ``` Examples of **incorrect** code for this rule with the `{ "beforeBlockComment": true, "allowClassStart": false }` option: ``` /\*eslint lines-around-comment: ["error", { "beforeBlockComment": true, "allowClassStart": false }]\*/ class foo { /\* what a great and wonderful day \*/ day() {} }; ``` Examples of **correct** code for this rule with the `{ "beforeBlockComment": true, "allowClassStart": false }` option: ``` /\*eslint lines-around-comment: ["error", { "beforeBlockComment": true, "allowClassStart": false }]\*/ class foo { /\* what a great and wonderful day \*/ day() {} }; ``` Examples of **correct** code for this rule with the `{ "beforeBlockComment": true, "allowClassStart": true }` option: ``` /\*eslint lines-around-comment: ["error", { "beforeBlockComment": true, "allowClassStart": true }]\*/ class foo { /\* what a great and wonderful day \*/ day() {} }; ``` ### allowClassEnd Examples of **correct** code for this rule with the `{ "afterLineComment": true, "allowClassEnd": true }` option: ``` /\*eslint lines-around-comment: ["error", { "afterLineComment": true, "allowClassEnd": true }]\*/ class foo { day() {} // what a great and wonderful day }; ``` Examples of **correct** code for this rule with the `{ "afterBlockComment": true, "allowClassEnd": true }` option: ``` /\*eslint lines-around-comment: ["error", { "afterBlockComment": true, "allowClassEnd": true }]\*/ class foo { day() {} /\* what a great and wonderful day \*/ }; ``` ### allowObjectStart Examples of **correct** code for this rule with the `{ "beforeLineComment": true, "allowObjectStart": true }` option: ``` /\*eslint lines-around-comment: ["error", { "beforeLineComment": true, "allowObjectStart": true }]\*/ var foo = { // what a great and wonderful day day: "great" }; const { // what a great and wonderful day foo: someDay } = {foo: "great"}; const { // what a great and wonderful day day } = {day: "great"}; ``` Examples of **correct** code for this rule with the `{ "beforeBlockComment": true, "allowObjectStart": true }` option: ``` /\*eslint lines-around-comment: ["error", { "beforeBlockComment": true, "allowObjectStart": true }]\*/ var foo = { /\* what a great and wonderful day \*/ day: "great" }; const { /\* what a great and wonderful day \*/ foo: someDay } = {foo: "great"}; const { /\* what a great and wonderful day \*/ day } = {day: "great"}; ``` ### allowObjectEnd Examples of **correct** code for this rule with the `{ "afterLineComment": true, "allowObjectEnd": true }` option: ``` /\*eslint lines-around-comment: ["error", { "afterLineComment": true, "allowObjectEnd": true }]\*/ var foo = { day: "great" // what a great and wonderful day }; const { foo: someDay // what a great and wonderful day } = {foo: "great"}; const { day // what a great and wonderful day } = {day: "great"}; ``` Examples of **correct** code for this rule with the `{ "afterBlockComment": true, "allowObjectEnd": true }` option: ``` /\*eslint lines-around-comment: ["error", { "afterBlockComment": true, "allowObjectEnd": true }]\*/ var foo = { day: "great" /\* what a great and wonderful day \*/ }; const { foo: someDay /\* what a great and wonderful day \*/ } = {foo: "great"}; const { day /\* what a great and wonderful day \*/ } = {day: "great"}; ``` ### allowArrayStart Examples of **correct** code for this rule with the `{ "beforeLineComment": true, "allowArrayStart": true }` option: ``` /\*eslint lines-around-comment: ["error", { "beforeLineComment": true, "allowArrayStart": true }]\*/ var day = [ // what a great and wonderful day "great", "wonderful" ]; const [ // what a great and wonderful day someDay ] = ["great", "not great"]; ``` Examples of **correct** code for this rule with the `{ "beforeBlockComment": true, "allowArrayStart": true }` option: ``` /\*eslint lines-around-comment: ["error", { "beforeBlockComment": true, "allowArrayStart": true }]\*/ var day = [ /\* what a great and wonderful day \*/ "great", "wonderful" ]; const [ /\* what a great and wonderful day \*/ someDay ] = ["great", "not great"]; ``` ### allowArrayEnd Examples of **correct** code for this rule with the `{ "afterLineComment": true, "allowArrayEnd": true }` option: ``` /\*eslint lines-around-comment: ["error", { "afterLineComment": true, "allowArrayEnd": true }]\*/ var day = [ "great", "wonderful" // what a great and wonderful day ]; const [ someDay // what a great and wonderful day ] = ["great", "not great"]; ``` Examples of **correct** code for this rule with the `{ "afterBlockComment": true, "allowArrayEnd": true }` option: ``` /\*eslint lines-around-comment: ["error", { "afterBlockComment": true, "allowArrayEnd": true }]\*/ var day = [ "great", "wonderful" /\* what a great and wonderful day \*/ ]; const [ someDay /\* what a great and wonderful day \*/ ] = ["great", "not great"]; ``` ### ignorePattern By default this rule ignores comments starting with the following words: `eslint`, `jshint`, `jslint`, `istanbul`, `global`, `exported`, `jscs`. To ignore more comments in addition to the defaults, set the `ignorePattern` option to a string pattern that will be passed to the [`RegExp` constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/RegExp). Examples of **correct** code for the `ignorePattern` option: ``` /\*eslint lines-around-comment: ["error"]\*/ foo(); /\* eslint mentioned in this comment \*/, bar(); /\*eslint lines-around-comment: ["error", { "ignorePattern": "pragma" }] \*/ foo(); /\* a valid comment using pragma in it \*/ ``` Examples of **incorrect** code for the `ignorePattern` option: ``` /\*eslint lines-around-comment: ["error", { "ignorePattern": "pragma" }] \*/ 1 + 1; /\* something else \*/ ``` ### applyDefaultIgnorePatterns Default ignore patterns are applied even when `ignorePattern` is provided. If you want to omit default patterns, set this option to `false`. Examples of **correct** code for the `{ "applyDefaultIgnorePatterns": false }` option: ``` /\*eslint lines-around-comment: ["error", { "ignorePattern": "pragma", applyDefaultIgnorePatterns: false }] \*/ foo(); /\* a valid comment using pragma in it \*/ ``` Examples of **incorrect** code for the `{ "applyDefaultIgnorePatterns": false }` option: ``` /\*eslint lines-around-comment: ["error", { "applyDefaultIgnorePatterns": false }] \*/ foo(); /\* eslint mentioned in comment \*/ ``` When Not To Use It ------------------ Many people enjoy a terser code style and don’t mind comments bumping up against code. If you fall into that category this rule is not for you. Related Rules ------------- * <space-before-blocks> * <spaced-comment> Version ------- This rule was introduced in ESLint v0.22.0. Resources --------- * [Rule source](https://github.com/eslint/eslint/blob/main/lib/rules/lines-around-comment.js) * [Tests source](https://github.com/eslint/eslint/blob/main/tests/lib/rules/lines-around-comment.js)
programming_docs