기본적으로는
#define A B
를 하면 그 다음부터 A라는 토큰을 모두 B로 치환한다.
#define toLongLong(i) static_cast<long long>(i)
위와 같이 함수처럼 사용할 수도 있다.
#ifdef와 #ifndef 를 사용하면 매크로가 정의되었는지 확인할 수 있다.
예시
인수명 앞에 #를 붙이면 문자열로 만들 수 있다. (== 큰따옴표로 묶는다.)
파라미터에 ...을 넣은 다음 대체할 내용에 __VA_ARGS__를 넣으면 ...에 해당되는 내용으로 치환된다. (쉼표 포함)
#define s(i) #i
#define invar(type, ...) type __VA_ARGS__; input(__VA_ARGS__)
template <typename ...T> void input(T&... a_) { (cin >> ... >> a_); }
int main() {
cout << s(Hello World);
// 위는 cout << "Hello World"; 로 치환된다.
invar(int, a, b, c);
// 위는 int a, b, c; input(a, b, c); 로 치환된다.
}
토큰 두 개를 중간에 공백 없이 이어붙인다.
#define func(type, i) func##type(i)
void funcA(int i) { cout << i << "A"; }
void funcB(int i) { cout << i << "B"; }
int main() {
func(A, 140); // 140A가 출력된다.
func(B, 120); // 120B가 출력된다.
}