More C++ Idioms/Int-To-Type

진영민·2022년 7월 9일
1

More C++ Idioms

목록 보기
2/10

1. 설명

c++의 함수를 overloading 할 때 사용하는 방법

단순히 이야기 하자면, int를 이용하여 서로 다른 type을 만드는 방법이다.
다른 int를 사용하면 다른 type이 된다.

static dispatching을 할 수 있다.

static dispatching

컴파일 시간에 호출될 함수를 결정하는 것, 런타임 시간에 그대로 실행하기 때문에
성능상 이점이 있음.

2. 코드

template <int I>
struct Int2Type
{
  enum { value = I };
};
-->by Andrei Alexandrescu

dynamic dispatching vs static dispatching

dynamic dispatching

class dynamicDispatching {
public:
    int type = 1;
};

void add(dynamicDispatching temp, int temp2) {
	if (temp.type == 1) {
	func();
	}
}

-->컴파일 시간에서는 add함수 안에서 if문에 걸리는지 체크할 수 없다.
따라서 런타임 시간에 if문을 확인하기 때문에 시간이 걸린다

static dispatching

template <int I>
struct Int2Type
{
	enum { value = I };
};

void add(Int2Type<1> temp,int temp2) {
	func()
}

-->Int2Type<1>은 이미 그 자체로 하나의 type이므로 if문 필요 없이 바로 함수를 실행할 수 있다.
따라서 성능상의 이점이 된다.

profile
코린이

0개의 댓글