Microsoft MVP성태의 닷넷 이야기
VC++: 132. enum 정의를 C++11의 enum class로 바꿀 때 유의할 사항 [링크 복사], [링크+제목 복사],
조회: 21892
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일

enum 정의를 C++11의 enum class로 바꿀 때 유의할 사항

기존 enum의 명확한 단점은 다음의 소스 코드로 알 수 있습니다.

enum TestMode
{
    OFF,
};

enum MyMode
{
    OFF, // Error C2365 'OFF': redefinition; previous definition was 'enumerator'
};

이 때문에, 어쩔 수 없이 Prefix를 정의해 함께 사용해야만 했습니다.

enum TestMode
{
    TM_OFF,
};

enum MyMode
{
    MM_OFF,
};

윈도우 헤더 파일에 정의된 수많은 enum 타입들의 상수가 왜 타입명을 함께 붙이고 정의하는지,

// windef.h

typedef enum DPI_AWARENESS {
    DPI_AWARENESS_INVALID           = -1,
    DPI_AWARENESS_UNAWARE           = 0,
    DPI_AWARENESS_SYSTEM_AWARE      = 1,
    DPI_AWARENESS_PER_MONITOR_AWARE = 2
} DPI_AWARENESS;

바로 이런 이유 때문이었던 것입니다.




그러다가, C++11 표준에서 "enum class"가 나와 더 이상 접미사가 필요 없게 되었습니다.

enum class TestMode
{
    ON,
    OFF,
};

enum class MyMode
{
    ON,
    OFF
};

int main()
{
    MyMode mode1 = MyMode::ON;
    MyMode mode2 = ON; // 컴파일 오류
}

하지만, 그래도 내부적으로는 "#define"과의 충돌을 해결하지 못해 다음과 같은 상황에서는 컴파일 오류가 발생합니다.

#define ON 100

enum class MyMode
{
    ON, // Error C2059 syntax error: 'constant'
    OFF
};

물론 이해는 됩니다. "ON"이라는 리터럴 자체를 #define 정의에 의해 모조리 치환하기 때문에 결국 다음과 같이 번역되므로 오류가 발생하는 것이 당연합니다.

#define ON 100

enum class MyMode
{
    100, // Error C2059 syntax error: 'constant'
    OFF
};

따라서 기존 헤더 파일에 같은 상수명이 정의되어 있다면 접미사를 붙이거나 명시적으로 #undef으로 해결할 수밖에 없습니다.

enum class TestMode
{
    TM_ON,
    OFF,
};

enum class MyMode
{
 #undef ON
    ON,
    OFF
};




enum class의 또 하나 문제점(?)이 있다면, 형식 안정성으로 인해 기존 enum이 int 타입 연산을 자연스럽게 할 수 있었던 것을 못하게 막는다는 점입니다. 즉, 다음과 같은 식의 비트 플래그 연산들이 enum class 사용 후부터 모두 오류가 발생하게 됩니다.

int main()
{
    MyMode mode1 = MyMode::ON;
    MyMode mode2 = MyMode::OFF;

    // Error C2676 binary '&': 'MyMode' does not define this operator or a conversion to a type acceptable to the predefined operator
    if ((mode1 & mode2) == mode2)
    {
    }
}

이 문제를 해결하려면 명시적인 int 형변환을 하거나,

if (((int)mode1 & (int)mode2) == (int)mode2)

"(int)" 형변환 따위의 코드 수정 없이 하고 싶다면, 좀 더 우아하게는 다음과 같이 연산자 재정의를 추가하면 됩니다.

inline MyMode operator&(MyMode& l, MyMode &r)
{
    return (MyMode)((int)l & (int)r);
}

inline MyMode operator|(MyMode& l, MyMode& r)
{
    return (MyMode)((int)l | (int)r);
}

멋스럽게 & 연산자를 추가해봤지만 저런 경우 다음과 같은 식의 상황에서는 컴파일 오류가 발생하므로,

auto GetFlags() -> MyMode
{
    return mode;
}

int main()
{
    MyMode mode = MyMode::ON;
    MyMode mode2 = MyMode::OFF;

    if ((mode | mode2) == mode2)
    {
        mode = MyMode::ON;
    }

    char* ptr = nullptr;

    // Error C2678 binary '&': no operator found which takes a left-hand operand of type 'MyMode' (or there is no acceptable conversion)
    if ((GetFlags() & mode2) == mode2)
    {
        mode = MyMode::ON;
    }
}

이 상황을 해결하기 위해 const 등의 좀 더 복잡한 코드를 만들 수도 있지만,

auto GetFlags() -> const MyMode&
{
    return mode;
}

inline MyMode operator&(const MyMode& l, MyMode &r)
{
    return (MyMode)((int)l & (int)r);
}

어차피 enum이 int 범위 내의 값이라는 특성을 감안하면 굳이 const로 만들지 않아도 된다는 점과, 오히려 ref를 받아 변경할 수 있도록 하는 것이 아니라면 애당초 그냥 아무 처리 없이 사용하는 것이 더 나은 선택일 것입니다.

inline MyMode operator&(MyMode l, MyMode r)
{
    return (MyMode)((int)l & (int)r);
}

inline MyMode operator|(MyMode l, MyMode r)
{
    return (MyMode)((int)l | (int)r);
}

(첨부 파일은 이 글의 예제 코드를 포함합니다.)




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 6/7/2019]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
14012정성태9/9/2025550닷넷: 2362. C# - Windows.Media.Ocr: 윈도우 운영체제에 포함된 OCR(Optical Character Recognition)파일 다운로드1
14011정성태9/7/20251020닷넷: 2361. C# - Linux 환경의 readlink 호출
14010정성태9/1/20251270오류 유형: 983. apt update 시 "The repository 'http://deb.debian.org/debian buster Release' does not have a Release file." 오류
14009정성태8/28/20251469닷넷: 2360. C# 14 - (11) Expression Tree에 선택적 인수와 명명된 인수 허용파일 다운로드1
14008정성태8/26/20251742닷넷: 2359. C# 14 - (10) 복합 대입 연산자의 오버로드 지원파일 다운로드1
14007정성태8/25/20252142닷넷: 2358. C# - 현재 빌드에 적용 중인 컴파일러 버전 확인 방법 (#error version)
14006정성태8/23/20252428Linux: 121. Linux - snap 패키지 관리자로 설치한 소프트웨어의 디렉터리 접근 제한
14005정성태8/21/20251934오류 유형: 982. sudo: unable to load /usr/libexec/sudo/sudoers.so: libssl.so.3: cannot open shared object file: No such file or directory
14004정성태8/21/20252159오류 유형: 981. dotnet 실행 시 No usable version of the libssl was found
14003정성태8/21/20252353닷넷: 2357. C# 14 - (9) 새로운 지시자 추가 (Ignored directives)
14002정성태8/20/20252483오류 유형: 980. C# - appsettings.json 파일의 설정값이 적용 안 된다면?
14001정성태8/19/20255054닷넷: 2356. .NET SDK 10 - 단일 소스 코드 파일을 빌드/실행하는 기능을 "dotnet" 명령어에 추가 [1]
14000정성태8/18/20252529오류 유형: 979. ERROR: failed to solve: failed to read dockerfile: open Dockerfile: no such file or directory
13999정성태8/15/20252562닷넷: 2355. C# 14 - (8) null 조건부 연산자 개선 - 대입문에도 사용 가능파일 다운로드1
13998정성태8/14/20252488닷넷: 2354. C# 14 - (7) 확장 메서드에 정적 메서드와 속성 지원을 위한 전용 구문 추가파일 다운로드1
13997정성태8/14/20252614Linux: 120. docker 컨테이너로 매핑된 볼륨에 컨테이너 측의 사용자 ID를 유지하면서 복사하는 방법
13996정성태8/13/20252094오류 유형: 978. Unable to find the requested .Net Framework Data Provider.
13995정성태8/13/20252237개발 환경 구성: 754. Visual C++ - 리눅스 빌드를 위한 Ubuntu 18 docker 컨테이너 설정
13994정성태8/12/20252050오류 유형: 977. SQL Server - User, group, or role '...' already exists in the current database. (Microsoft SQL Server, Error: 15023)
13993정성태8/11/20252768오류 유형: 976. Microsoft.ML.OnnxRuntimeGenAI 패키지 사용 시 "cublasLt64_12.dll" which is missing. (Error 126: "The specified module could not be found.") 오류
13992정성태8/11/20252804닷넷: 2353. C# - Foundry Local을 이용한 gpt-oss-20b 모델 사용파일 다운로드1
13991정성태8/9/20252545오류 유형: 975. winget - Foundry Local 패키지 업데이트가 안 되는 문제
13990정성태8/8/20252056Windows: 283. Time zone 설정이 없는 Windows Server 2025
13989정성태8/8/20252748닷넷: 2352. C# - Windows S-mode 환경인지 체크하는 방법파일 다운로드1
13988정성태8/8/20252800오류 유형: 974. 비주얼 스튜디오 업데이트 시 잠김 파일 경고 - Visual Studio Standard Collector Service 150 (VSStandardCollectorService150)
[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...