Notice
Recent Posts
Recent Comments
Link
| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | |||||
| 3 | 4 | 5 | 6 | 7 | 8 | 9 |
| 10 | 11 | 12 | 13 | 14 | 15 | 16 |
| 17 | 18 | 19 | 20 | 21 | 22 | 23 |
| 24 | 25 | 26 | 27 | 28 | 29 | 30 |
| 31 |
Tags
- C++
- GPIO
- raspberrypi
- Debug
- 회로
- vscode
- 아두이노
- yocto
- 라즈베리파이
- Visual Studio Code
- Debugging
- Linux
- AArch64
- esp32
- cpp
- c#
- 디버깅
- atmel
- STM32
- UART
- AVR
- Visual Studio
- nucleo
- Raspberry
- bare metal
- QEMU
- WPF
- Arduino
- avr-gcc
- buildroot
Archives
- Today
- Total
임베디드를 좋아하는 조금 특이한 개발자?
[C++] 사용자 정의 리터럴 (operator "") 본문
- 참고 문서
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;
}

'C++' 카테고리의 다른 글
| [C++] std::bind 함수를 원하는 호출 형태로 가공 (0) | 2026.03.24 |
|---|---|
| [C++20 : Chrono.h] system_clock를 사용한 현재 시간 구하기 (0) | 2026.03.22 |
| [Visual Studio Code] C++ 자동완성(Autocomplete) 기능 활성화 (0) | 2026.03.09 |
| accumulate() 함수의 overflow 문제 해결 방법 (0) | 2025.01.21 |
| rel_ops를 통한 클래스 비교연산자 자동 구현 (0) | 2022.08.28 |