2013-04-12 2 views
1

템플릿을 사용해야하는 곳에서 프로그램을 만들려고하고 있으며 잠시 동안 고생하고 있습니다. 여기 내 코드의 일부는 다음과 같습니다다양한 유형의 기본 템플릿 인수

template <typename _Type, typename _Comparator = equal_to</*char*/> > 
     class CSearch { 
public: 
    CSearch(); 
    CSearch(const _Comparator & cmp); 
    void Add(int id, 
      const _Type & needle); 
    set<int> Search(const _Type & hayHeap) const; 
private: 

    struct CSElem { 
     int id; 
     _Type sekvence; 
    }; 
    vector<CSElem> data; 
    _Comparator comp; 
}; 

template <typename _Type, typename _Comparator> 
CSearch<_Type, _Comparator>::CSearch() { 
    comp = _Comparator(); 
} 

....... 

template <typename _Type, typename _Comparator> 
void CSearch<_Type, _Comparator>::Add(int id, const _Type& needle) { 
    CSElem temp; 

    ..... 

    data.push_back(temp); 
} 

template <typename _Type, typename _Comparator> 
set<int> CSearch<_Type, _Comparator>::Search(const _Type& hayHeap) const { 
typename _Type::const_iterator j, t; 

    ...... //trying to find out which items of the variable data are part of hayHeap 

        if (comp(*t, *j)) { 
         ...... 
        } 

    ...... 

} 

/* 
* 
*/ 
int main(int argc, char** argv) { 
    CSearch <string> test1; 
    test1 . Add(0, "hello"); 
    test1 . Add(1, "world"); 
    test1 . Search("hello world!"); 

    CSearch <vector<int> > test2; 

.... 

} 

그래서 문제는 템플릿에 두 번째 매개 변수를 제공하지 않는 경우, 비교기는 문자열 있도록 테스트 변수에 저장되어있는 유형 equal_to해야한다는 것입니다 이

equal_to<char> 

또는 int 치의

여전히
equal_to<int> 

내가 오래 동안 그것에 대해 생각되었고, 벡터를 위해해야하는 템플릿 또는 w를 선언하는 방법을 생각하지 않은 모자를 써서 이전에 언급 한 기능이 있습니다. 누군가가 나에게이 문제를 해결할 수있는 힌트 또는 예제를 줄 수 있다면 매우 행복 할 것입니다.

감사

답변

4

당신은 후속 템플릿 매개 변수에 대한 기본 인수를 형성하기 위해 템플릿 서명에 이전 템플릿 매개 변수를 사용할 수 있습니다. 또한, 모든 표준 컨테이너가 포함 된 요소의 유형에 대한 value_type 별명을 정의한다는 사실을 악용 할 수 있습니다

template <typename _Type, 
      typename _Comparator = equal_to<typename _Type::value_type> > 
//              ^^^^^^^^^^^^ 

std::string들도 멤버 함수와 그들을의 일반적인 알고리즘에 의해 사용할 수 있도록 유형 별칭이 C++ 표준 라이브러리이므로 _Typestd::string 일 때도 위와 같이 작동합니다.

+0

오, 감사합니다. 저는 value_type 별칭에 대해 알지 못했지만, 확실히 그 일을했습니다 :). – user2274361

+0

@ user2274361 : 기꺼이 도와 줬습니다. 프로젝트에 행운이 있기를 바랍니다. –

0

템플릿 정의에 대해이 작업을 시도해보십시오

template <typename _Type, typename _Comparator = equal_to<_Type> > 
0

또한 또한 _ 할 수 Container 템플릿 템플릿 매개 변수를.

template <typename _Type, template <typename> class _Comparator = equal_to > 
class CSearch { 
public: 
    typedef typename _Type::value_type elem_type; 
    CSearch(); 
    CSearch(const _Comparator<elem_type> & cmp); 
    void Add(int id, 
      const _Type & needle); 
    set<int> Search(const _Type & hayHeap) const; 
private: 

    struct CSElem { 
     int id; 
     _Type sekvence; 
    }; 
    vector<CSElem> data; 
    _Comparator<elem_type> comp; 
};