8.15 Function templates with multiple template types

주홍영·2022년 3월 13일
0

Learncpp.com

목록 보기
91/199

https://www.learncpp.com/cpp-tutorial/function-templates-with-multiple-template-types/

template을 활용할 때 복수의 template type을 사용할 수 있다

#include <iostream>

template <typename T, typename U> // We're using two template type parameters named T and U
T max(T x, U y) // x can resolve to type T, and y can resolve to type U
{
    return (x > y) ? x : y; // uh oh, we have a narrowing conversion problem here
}

int main()
{
    std::cout << max(2, 3.5) << '\n';

    return 0;
}

Abbreviated function templates C++20

c++ 20에서 지원하는 문법에 관한 설명이다
예를들어

auto max(auto x, auto y)
{
    return (x > y) ? x : y;
}

이는 다음과 같다

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

참고로 c++14부터는 함수의 리턴타입을 컴파일러가 알아서 지정할 수 있다. (auto return type)

profile
청룡동거주민

0개의 댓글