template <>

Jinyeong Choi·2024년 6월 17일

C++

목록 보기
5/5

Generic Function

Not a Specific term, Generic term.

#include <iostream>

template<typename T> // <class T>와 동일한 표현
bool less_than(T a, T b) {
	if (a < b) {
		return true;
	}
	return false;
}

int main() {
	int a = 2, b = 5;
	std::cout << less_than(a, b) << '\n';
}
  • T: type parameter
  • Specific functions are generated by C++ automatically.
#include <iostream>

template <int N>
int scale(int value) {
	return value * N;
}

int main() {
	std::cout << scale<3>(5) << std::endl;
	std::cout << scale<2>(10) << std::endl;
}

Class Template

#include <iostream>
#include <string>

template <typename T>
class Point {
public:
	T x; T y;
	Point(T x_, T y_) : x(x_), y(y_) {}
};

int main() {
	Point<int> pixel1(10, 10);
	Point<double> pixel2(2.4, 20.1);
}
  • Rather than providing two separate classes, we can write one class template let the compiler instantiate the coordinates as the particular program requires.
  • With class templates we can specify the pattern or structure of a class of objects in a type-independent way.
profile
Hang in there

0개의 댓글