C++의 템플릿

4698 단어 cpp

C++ 언어의 템플릿



키워드template는 C++ 프로그램에서 함수 템플릿과 클래스 템플릿을 정의하는 데 사용됩니다.
프로그래머가 보다 효율적인 코드를 작성할 수 있는 방법을 만드는 일반 프로그래밍을 소개합니다.

이제 템플릿을 사용할 수 있는 두 가지 방법이 있습니다.

  • 기능 템플릿



    함수 템플릿은 일반 함수라고도 합니다.
  • syntax 함수 템플릿 생성:

    template<class type> 
    type func_name(type arg1, type arg2, ....){
         ...
    };
    // here type is a placeholder for generalisation of data type.
    


    임의 개수의 인수를 사용하여 이름이 func_name인 함수 템플릿을 생성합니다.

    예를 들어 알아보겠습니다.
    template *를 사용하지 않고 주어진 두 숫자*에서 더 작은 숫자를 찾는 프로그램:

    #include<iostream>
    
    using namespace std;
    
    // without the use of template keyword.
    int small(int a, int b){
        if(a > b){
            return(b);    
        }else{
            return(a);
        }
    };
    
    double small(double a, double b){ // function overloading
        if(a > b){
            return(b);
        }else{
            return(a);
        }
    };
    
    
    int main(){
        cout<<small(2,6)<<endl;
        cout<<small(2.4,1.9);
        return 0;
    }
    
    /*
    OUTPUT
    2
    1.9
    */
    


    (코드 32줄)

    함수에서 다른 데이터 유형을 사용하지 않으려면 template 를 사용하십시오.

    #include<iostream>
    
    using namespace std;
    
    // Program using template keyword
    template<class X>
    X small(X a, X b){ // here X is a generic data type, making 'small' a generic function.
        if(a < b){
            return(b);
        }else{
            return(a);
        }
    };
    
    int main(){
        cout<<small(3,4)<<endl;
        cout<<small(3.4,1.6); // no function overloading reduces the lines of code in a program
        return 0;
    }
    
    /*
    OUTPUT
    3
    1.6
    */
    
    


    (코드 25줄)

    예 2:

    template<class X, class Y>  
    X big(X a, Y b){        //different data types
        if(a > b){
            return a;
        }else{
            return b;
        }
    };
    
    int main(){
        cout<<big(4,3.4)<<endl;
        cout<<big(1.99,-5);
        return 0;
    }
    
    /*
    OUTPUT:
    4
    1.99
    */
    
    


    (코드 20줄)

  • 클래스 템플릿



    클래스 템플릿은 제네릭 클래스라고도 합니다.


  • template<class type> 
    class class_name{
        ...
    };
    // here type is also a placeholder to generalise a class.
    

    class_name 라는 클래스 템플릿을 만듭니다.

    이것도 예를 들어 알아봅시다.
    여기서 우리는 템플릿을 사용하지 않고 arrayList 클래스를 만들고 있습니다.

    #include<iostream>
    
    using namespace std;
    
    class arrayList{
        private:
            struct controlBlock{
                int capacity;
                int *arr_ptr;
            };
    
        controlBlock *s;
    
        public:
            arrayList(int capacity){ // constructor of arrayList class
                s = new controlBlock;
                s -> capacity = capacity;
                s -> arr_ptr = new int[s->capacity];
            }
            void addElement(int index, int data){ // method to add elements to the list
                if(index >= 0 && index <= s->capacity - 1){
                    s -> arr_ptr[index]  = data;
                }else{
                    cout<<"Array index not valid";
                }
            }
            void viewElement(int index, int &data){
                if(index >=0 && index <= s->capacity - 1){
                    data = s->arr_ptr[index];
                }else{
                    cout<<"Array index not valid";
                }
            }
            void viewList(){ // method to view the list
                int i;
                for(i = 0; i < s->capacity; i++){
                    cout<<" "<<s->arr_ptr[i];
                }
            }
    };
    
    int main(){
        int data;
        arrayList list1(4);
        list1.addElement(0,2);
        list1.addElement(1,12);
        list1.addElement(2,22);
        // list1.addElement(3,32); if not assigned, by default 0 is assigned.
        // list1.viewElement(0,data);
        // cout<<data;
        list1.viewList();
        return 0;
    }
    
    /*
    OUTPUT:
    2
    12
    22
    0
    */
    


    (61줄의 코드)

    코드의 이미지 설명.



    이제 위의 프로그램을 템플릿화하면 같은 수의 코드로 입력 가능성이 높아집니다.

    방문 : arrayList_with_template.cpp

    에서 STL에 대해 읽어보십시오.

    좋은 웹페이지 즐겨찾기