함수 템플릿
Coddy의 C 개발자를 위한 C++ 코스 레슨. 48개 중 25번째.
C에서는 재사용 가능한 연산을 작성하기 위해 매크로나 void 포인터를 자주 사용하며, 이 과정에서 일부 타입 검사를 포기합니다. C++ 템플릿은 인스턴스화될 때 타입이 지정된 함수나 클래스를 생성합니다. 각 번역 단위에서 필요한 특수화를 인스턴스화할 수 있도록 정의는 보통 헤더에 둡니다.
C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
int twice_int(int n){return n+n;}
int main(void){
printf("%d\n",twice_int(3));
return 0;
}
C++
#include <iostream>
#include <string>
#include <vector>
#include <array>
#include <map>
#include <set>
#include <algorithm>
#include <memory>
#include <sstream>
#include <stdexcept>
#include <utility>
template<class T>T twice(T value){return value+value;}
int main(){
std::cout<<twice(3)<<" "<<twice(std::string("ha"))<<"\n";
}
각 프로그램을 독립적으로 추적해 보세요. 이 예제들은 과제와 다른 연산이나 데이터를 사용해 개념을 보여 줍니다. 소스 코드의 출력과 대상 코드의 출력이 일치한다고 가정하지 마세요.
챌린지
쉬움입력: 두 정수. 헤더에서 순서가 있는 자료형에 대해 smaller를 구현하세요. 문자열을 사용하는 독립적인 테스트를 포함해 더 작은 인수를 반환하세요.
exercise.hpp와 exercise.cpp에 선언된 API를 구현하세요. 두 파일 모두 편집할 수 있습니다. 공개 시그니처는 그대로 유지하세요. 잠긴 main.cpp는 표준 입력을 읽고 API를 직접 호출합니다. 또한 명시된 경우 공개 API의 동작을 독립적으로 확인합니다. API 내부에서 출력하지 말고 값을 반환하세요. 정수 입력과 결과는 부호 있는 int 범위에 들어갑니다. 별도 언급이 없는 한 텍스트는 ASCII입니다.
직접 해보기
#include "exercise.hpp"
#include <iostream>
int main(){
{if(smaller(std::string("z"),std::string("a"))!="a")return 21;}
std::vector<std::string> rows; std::string line; while(std::getline(std::cin,line)) rows.push_back(line);
std::istringstream in(rows.empty()?"":rows[0]);int a,b;in>>a>>b;std::cout<<smaller(a,b)<<"\n";
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
C 개발자를 위한 C++의 모든 레슨
직접 연습해 보세요: 온라인 C++ 컴파일러