2014-03-06 4 views
2

벡터,리스트, 세트를 다루는 함수 템플릿을 쓰고 싶습니다. 지도를 별도로 처리하는 특수화 함수를 쓰고 싶습니다. 다음 코드를 작성하고 컴파일러가 오류를보고합니다.템플레이트를 인수로 사용할 때 함수 템플릿 전문화

수정 방법을 알려주세요.

#include <iostream> 
#include <string> 
#include <map> 
#include <unordered_map> 
using namespace std; 

// test() for the vectors, lists, sets, ... 

template <template <typename...> class T> 
void test() 
{ 
    T<string, int> x; 
    //... 
} 

// specialize test() for map 
template <> 
void test <map<> class T>() 
{ 

    T<string, int> x; 
    //... 
} 


int main() 
{ 
    test<map>(); 
    test<unordered_map>(); 
} 
+2

어떤 종류의? – songyuanyao

+0

; --------- 이전 코드를 컴파일하기 위해 code :: blocks + gcc4.7.1을 사용할 때 다음과 같은 오류가 발생합니다. mingw32-g ++. exe -Wall -fexceptions -std = C++ 11 -g -c main.cpp -o obj \ Debug \ main.o main.cpp : 138 : 16 : 오류 : 잘못된 템플릿 수 (0, 4 여야 함) c : \ mingw \ bin ../ lib에 포함 된 파일 main.cpp : 11 : c : \ mingw \ bin ../lib/gcc/mingw32/4.7.1/include/C++/bits에서 /gcc/mingw32/4.7.1/include/c++/map:61:0/무효 : test : 'void test()'에 대한 템플릿 ID 'test < >'이 (가) 템플릿과 일치하지 않습니다. 선언 – shavian

답변

2

템플릿 특성화 같아야

template <> 
void test <std::map>() 
{ 

    std::map<string, int> x; 
} 

제가 std::map에 잘못된 구문은 map<> class T에서 템플릿 파라미터를 변경. 그리고 전문화에 T 이름이 없으므로 T<string, int>std::map<string, int>으로 변경했습니다.

+0

많은 감사와 그 일을 지금하십시오. – shavian

0

다음은 작동하는 전체 코드 : 오류의

#include <iostream> 
#include <string> 
#include <map> 
#include <unordered_map> 
using namespace std; 

template <template <typename...> class T, typename TN> 
void test() 
{ 
    cout << "---------- test case 1" << endl; 
    T<TN, int> x; 
} 

template <template <typename...> class T> 
void test() 
{ 
    cout << "---------- test case 2" << endl; 
    T<string, int> x; 
} 

template <> 
void test < map,string >() 
{ 
    cout << "---------- test case 3" << endl; 
    map<string, int> x; 
} 

template <> 
void test <map>() 
{ 
    cout << "---------- test case 4" << endl; 
    map<string, int> x; 
} 

int main() 
{ 
    test<unordered_map,string>(); // trigging test case 1 
    test<unordered_map>();  // trigging test case 2 
    test<map,string>();   // trigging test case 3 
    test<map>();     // trigging test case 4 
} 
관련 문제