8.14 Function template instantiation

주홍영·2022년 3월 13일
0

Learncpp.com

목록 보기
90/199

https://www.learncpp.com/cpp-tutorial/function-template-instantiation/

이전 섹션에서 function template에 대해서 간단하게 설명했고
이번 섹션에서는 어떠한 형태로 사용하는지 살펴본다
형태는 다음과 같다

#include <iostream>

template <typename T>
T max(T x, T y)
{
    return (x > y) ? x : y;
}

int main()
{
    std::cout << max<int>(1, 2) << '\n'; // instantiates and calls function max<int>(int, int)

    return 0;
}

기타 자잘한 활용법에 대해서 이야기하고 있다
예를들어 type을 생략하고 type deduction을 이용해 사용한다던가...
하지만 정석적인 방법이 아니므로 생략하겠다

template으로 function call을 하는 것은
이미 definition된 함수를 사용하는 것이 아니다
따라서 max< int >(1,2) 와 같은게 실행될 때
새로 정의된 함수를 만드는 것이다
이러한 process를 function template instantiation이라고 한다
한번 instantiate된 function의 형태는 그대로 남아 있으므로
똑같은 type으로 새로 만든다면 추가로 instantiate 하지 않는다

Generic programming

Because template types can be replaced with any actual type, template types are sometimes called generic types. And because templates can be written agnostically of specific types, programming with templates is sometimes called generic programming. Whereas C++ typically has a strong focus on types and type checking, in contrast, generic programming lets us focus on the logic of algorithms and design of data structures without having to worry so much about type information.

타입에 너무 구애받지 않고 알고리즘과 자료형에 신경쓸 수 있도록 도와준다

profile
청룡동거주민

0개의 댓글