임베디드를 좋아하는 조금 특이한 개발자?

[C++] 사용자 정의 리터럴 (operator "") 본문

C++

[C++] 사용자 정의 리터럴 (operator "")

Gordon_ 2026. 3. 22. 21:58

- 참고 문서

https://en.cppreference.com/w/cpp/language/user_literal.html

 

User-defined literals (since C++11) - cppreference.com

Allows integer, floating-point, character, and string literals to produce objects of user-defined type by defining a user-defined suffix. [edit] Syntax A user-defined literal is an expression of any of the following forms decimal-literal ud-suffix (1) octa

en.cppreference.com

 

1. 서론

  chrono 관련 기능을 확인하던 중 매우 재미있는 문법을 발견하여 소개해드립니다. 리터럴 상수 뒤에 특정 문자를 결합하여 상수의 형을 정할 수 있습니다. 예를 들어 10u의 경우 unsigned int라는 형으로 설정됩니다. 하지만 C++에서는 이조차도 operator로 사용자가 원하는 리터럴 상수를 만들 수 있도록 하였습니다.

사용자 지정 리터럴를 사용할 수있는 변수 타입

 

   사용 가능한 변수 타입이 정해져 있습니다. 그러므로 위 타입들만으로 사용해야 합니다.(int 사용 불가능)

 

  constexpr를 같이 써 주어야 컴파일 타임에 값이 결정됩니다. 그러므로 되도록 constexpr를 붙여 주는 것이 좋습니다.

2. 예제

#include <iostream>

using namespace std;

constexpr uint64_t operator""KB(uint64_t KiloByte){
    return KiloByte * (2 << 9);
}

constexpr uint64_t operator""MB(uint64_t KiloByte) {
    return KiloByte * (2 << 19);
}

constexpr uint64_t operator""GB(uint64_t KiloByte) {
    return KiloByte * (2 << 29);
}

int main()
{

    cout << "1KB = " << 1KB << "bytes" << endl;
    cout << "1MB = " << 1MB << "bytes" << endl;
    cout << "1GB = " << 1GB << "bytes" << endl;
    
    return 0;
}

결과