Computer >> 컴퓨터 >  >> 프로그램 작성 >> C++

C++의 템플릿 전문화

<시간/>

C++에서 템플릿은 일반화된 함수와 클래스를 만드는 데 사용됩니다. 따라서 int, char, float 또는 템플릿을 사용하는 일부 사용자 정의 데이터와 같은 모든 유형의 데이터를 사용할 수 있습니다.

이 섹션에서는 템플릿 전문화를 사용하는 방법을 살펴보겠습니다. 이제 다양한 유형의 데이터에 대해 일반화된 템플릿을 정의할 수 있습니다. 그리고 특별한 유형의 데이터를 위한 몇 가지 특별한 템플릿 기능. 더 나은 아이디어를 얻기 위해 몇 가지 예를 살펴보겠습니다.

예시 코드

#include<iostream>
using namespace std;
template<typename T>
void my_function(T x) {
   cout << "This is generalized template: The given value is: " << x << endl;
}
template<>
void my_function(char x) {
   cout << "This is specialized template (Only for characters): The given value is: " << x << endl;
}
main() {
   my_function(10);
   my_function(25.36);
   my_function('F');
   my_function("Hello");
}

출력

This is generalized template: The given value is: 10
This is generalized template: The given value is: 25.36
This is specialized template (Only for characters): The given value is: F
This is generalized template: The given value is: Hello

템플릿 전문화는 클래스에 대해서도 생성할 수 있습니다. 일반화 클래스와 특화 클래스를 생성하여 한 가지 예를 살펴보겠습니다.

예시 코드

#include<iostream>
using namespace std;
template<typename T>
class MyClass {
   public:
      MyClass() {
         cout << "This is constructor of generalized class " << endl;
      }
};
template<>
class MyClass <char>{
   public:
      MyClass() {
         cout << "This is constructor of specialized class (Only for characters)" << endl;
      }
};
main() {
   MyClass<int> ob_int;
   MyClass<float> ob_float;
   MyClass<char> ob_char;
   MyClass<string> ob_string;
}

출력

This is constructor of generalized class
This is constructor of generalized class
This is constructor of specialized class (Only for characters)
This is constructor of generalized class