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) 생성자가 또는 변환 함수 (C++11부터) 또는 deduction guide (C++17부터) explicit임을 지정합니다. 즉, implicit conversions copy-initialization 에 사용할 수 없습니다.
2) explicit 지정자는 상수 표현식과 함께 사용될 수 있습니다. 해당 상수 표현식이 true 로 평가되는 경우에만 함수가 explicit입니다.
(C++20부터)

explicit 지정자는 생성자의 선언 decl-specifier-seq 내부에서만 나타날 수 있으며, 또는 변환 함수 (C++11부터) 해당 클래스 정의 내에서만 사용됩니다.

참고 사항

생성자 단일 비기본 매개변수를 가진 (C++11 이전) explicit 함수 지정자 없이 선언된 경우, 변환 생성자 라고 합니다.

(복사 생성자와 이동 생성자를 제외한) 다른 생성자들과 사용자 정의 변환 함수는 함수 템플릿일 수 있습니다; 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) {}      // 변환 생성자
    A(int, int) {} // 변환 생성자 (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: 복사 초기화는 A::A(int)를 선택함
    A a2(2);       // OK: 직접 초기화는 A::A(int)를 선택함
    A a3 {4, 5};   // OK: 직접 목록 초기화는 A::A(int, int)를 선택함
    A a4 = {4, 5}; // OK: 복사 목록 초기화는 A::A(int, int)를 선택함
    A a5 = (A)1;   // OK: 명시적 캐스트는 static_cast를 수행함
    if (a1) { }    // OK: A::operator bool()
    bool na1 = a1; // OK: 복사 초기화는 A::operator bool()를 선택함
    bool na2 = static_cast<bool>(a1); // OK: static_cast는 직접 초기화를 수행함
//  B b1 = 1;      // 오류: 복사 초기화는 B::B(int)를 고려하지 않음
    B b2(2);       // OK: 직접 초기화는 B::B(int)를 선택함
    B b3 {4, 5};   // OK: 직접 목록 초기화는 B::B(int, int)를 선택함
//  B b4 = {4, 5}; // 오류: 복사 목록 초기화는 B::B(int, int)를 고려하지 않음
    B b5 = (B)1;   // OK: 명시적 캐스트는 static_cast를 수행함
    if (b2) { }    // OK: B::operator bool()
//  bool nb1 = b2; // 오류: 복사 초기화는 B::operator bool()를 고려하지 않음
    bool nb2 = static_cast<bool>(b2); // OK: static_cast는 직접 초기화를 수행함
    [](...){}(a4, a5, na1, na2, b5, nb2); // "사용되지 않은 변수" 경고를 억제함
}

참고 항목