https://stackoverflow.com/questions/10747810/what-is-the-difference-between-typedef-and-using-in-c11
What is the difference between 'typedef' and 'using' in C++11?
I know that in C++11 we can now use using to write type alias, like typedefs: typedef int MyInt; Is, from what I understand, equivalent to: using MyInt = int; And that new syntax emerged from the
stackoverflow.com
레이트레이싱 예제를 보다가 using을 통해 클래스에 대해 별칭을 선언해 주는 부분을 보았는데 typedef의 존재가 생각나서 찾아보게 되었다.
코드
//기본 타입형
//typedef
typedef vec3 point3
//using
using point3 = vec3
//함수
//typedef
typedef void (&MyFunc)(int,int);
//using
using MyFunc = void(&)(int,int);
//템플릿
//typedef
template <typename T>
struct vector3D
{
typedef vector<T> vec3;
};
vector3D<int>::vec3 point3 { int x, int y, int z };
//using
template <typename T>
using vector3D = vector<T>;
vector3D<int> point3 { int x, int y, int z };
검색을 좀 해 본 결과 대부분의 답변이 비슷했다.(결론 부분에 정리)
아래의 댓글 내용만 좀 더 자세히 설명해주는 것 같았다.
동일하지만 허용되는 컨텍스트의 미묘한 차이
"두 가지 variation이 사용될 수 있는 context와 관련하여 동일한 제한을 갖는다는 것을 의미 하지는 않습니다."
typedef(init-statement) - 초기화 문을 허용하는 컨텍스트에서 사용할 수 있다.
using(alias-declaration) - init-statement가 아니므로 초기화 문을 허용하는 문맥에서는 사용할 수 없다.
댓글 아래에 여러가지 예시를 들어줬는데 솔직히 예시를 봐도 잘 모르겠다.
나중에 C++을 좀 더 깊게 공부하고 다시 봐야될 것 같다.
결론
이해한 내용만 정리하면 다음과 같다.
- 동일한 의미, 같은 역할을 수행하는 키워드
- 매번 구조체를 선언해야하는 typedef와 달리 using은 템플릿(template)을 편하게 사용가능하다는 점에서 이점이 있다.
- using의 '=' 기호가 구분자(delimiter) 역할을 하게 되어 typedef에 비해 코드 가독성이 좋아진다.
결론 : 언어 표준이 새롭게 갱신된 using을 사용하자.
'C/C++' 카테고리의 다른 글
Struct의 구조체 Padding에 대해 알아보자 (0) | 2023.08.23 |
---|---|
C/C++ 을 편하게 해주는 Visual Studio 단축키 (0) | 2023.08.04 |