Namespaces
Variants

explicit specifier

From cppreference.net
C++ language
General topics
Flow control
Conditional execution statements
Iteration statements (loops)
Jump statements
Functions
Function declaration
Lambda function expression
inline specifier
Dynamic exception specifications ( until C++17* )
noexcept specifier (C++11)
Exceptions
Namespaces
Types
Specifiers
constexpr (C++11)
consteval (C++20)
constinit (C++20)
Storage duration specifiers
Initialization
Expressions
Alternative representations
Literals
Boolean - Integer - Floating-point
Character - String - nullptr (C++11)
User-defined (C++11)
Utilities
Attributes (C++11)
Types
typedef declaration
Type alias declaration (C++11)
Casts
Memory allocation
Classes
Class-specific function properties
explicit (C++11)
static

Special member functions
Templates
Miscellaneous

Содержание

Синтаксис

explicit (1)
explicit ( expression ) (2) (начиная с C++20)
expression - контекстно преобразованное константное выражение типа bool


1) Указывает, что конструктор или преобразующая функция (since C++11) или deduction guide (since C++17) является explicit, то есть не может использоваться для неявных преобразований и копирующей инициализации .
2) Спецификатор explicit может использоваться с константным выражением. Функция является explicit тогда и только тогда, когда это константное выражение вычисляется в true .
(since C++20)

Спецификатор explicit может появляться только в decl-specifier-seq объявления конструктора или функции преобразования (начиная с C++11) внутри определения его класса.

Примечания

Конструктор с единственным не-умолчательным параметром (до C++11) , объявленный без спецификатора функции explicit , называется converting constructor .

Оба конструктора (кроме copy / move ) и пользовательские функции преобразования могут быть шаблонами функций; значение explicit не меняется.

Токен ( следующий за explicit всегда парсится как часть explicit-спецификатора:

struct S
{
    explicit (S)(const S&);    // error in C++20, OK in C++17
    explicit (operator int)(); // error in C++20, OK in C++17
};
(начиная с C++20)
Макрос тестирования возможностей Значение Стандарт Возможность
__cpp_conditional_explicit 201806L (C++20) условный explicit

Ключевые слова

explicit

Пример

struct A
{
    A(int) {}      // converting constructor
    A(int, int) {} // converting constructor (C++11)
    operator bool() const { return true; }
};
struct B
{
    explicit B(int) {}
    explicit B(int, int) {}
    explicit operator bool() const { return true; }
};
int main()
{
    A a1 = 1;      // OK: copy-initialization selects A::A(int)
    A a2(2);       // OK: direct-initialization selects A::A(int)
    A a3 {4, 5};   // OK: direct-list-initialization selects A::A(int, int)
    A a4 = {4, 5}; // OK: copy-list-initialization selects A::A(int, int)
    A a5 = (A)1;   // OK: explicit cast performs static_cast
    if (a1) { }    // OK: A::operator bool()
    bool na1 = a1; // OK: copy-initialization selects A::operator bool()
    bool na2 = static_cast<bool>(a1); // OK: static_cast performs direct-initialization
//  B b1 = 1;      // error: copy-initialization does not consider B::B(int)
    B b2(2);       // OK: direct-initialization selects B::B(int)
    B b3 {4, 5};   // OK: direct-list-initialization selects B::B(int, int)
//  B b4 = {4, 5}; // error: copy-list-initialization does not consider B::B(int, int)
    B b5 = (B)1;   // OK: explicit cast performs static_cast
    if (b2) { }    // OK: B::operator bool()
//  bool nb1 = b2; // error: copy-initialization does not consider B::operator bool()
    bool nb2 = static_cast<bool>(b2); // OK: static_cast performs direct-initialization
    [](...){}(a4, a5, na1, na2, b5, nb2); // suppresses “unused variable” warnings
}

Смотрите также