2012-04-03 39 views
1

我寫了這個小碼爲什麼在STL地圖模板中使用模板作爲參數會被拒絕?

std::map<int,template<class T>> map_; 
map_.insert(make_pair<int,message>(myMsg.id,myMsg)); 

但是編譯器似乎並沒有得到它,並顯示爲錯誤

template argument 2 is invalid 

,當我試圖做這個

template<class T> 
std::map<int,T> map_; 
糾正

它顯示爲一個錯誤:

expected primary-expression before 'template' |

error: expected ';' before 'template'

+3

什麼是它應該做的?請注意,模板必須始終在編譯時解析。看來你想用它們來構建一個多態的容器,這是不可能的;你必須爲此使用虛擬繼承。 – leftaroundabout 2012-04-03 10:47:46

+0

實際上,我應該在地圖中存儲每種類型的消息,所以我嘗試通過「std :: map > map_;」調用它來創建全局結構。 (它也不工作),所以class可以是message_typeA,message_typeB等 – Glolita 2012-04-03 12:06:14

+0

正如我所說的那樣,這是不可能的。製作'message_typeA','message_typeB'派生的類爲'messegetype_base',然後你就可以使用一個容器。 'std :: unique_ptr's到這些對象中的任何一個。這比動態語言(或者至少是垃圾收集的)要複雜一些,但它確實有它的好處(編譯時類型安全,性能良好......)。 – leftaroundabout 2012-04-03 12:23:09

回答

3

我對此不太確定,但是您正在嘗試聲明一個變量,並且該定義必須完全定義。試圖使用模板不能完全定義變量。

您可以在一個結構把它包起來,如果你想:

template<typename T> 
struct Wrapper 
{ 
    typedef std::map<int, T> map_type; 
}; 

然後使用它是這樣的:

Wrapper<std::string>::map_type my_wrapped_map; 
my_wrapped_map[1] = "Foo"; 
+0

非常感謝,很好,但我試圖添加另一個字段到這個結構「typedef std :: map :: iterator map_type_iter;」但它顯示一個錯誤,我不能得到它的錯誤! – Glolita 2012-04-03 15:25:44

0

你可能沒有使用C++編譯器11,這行是無效的:

std::map<int,template<class T>> map_; 

應該

std::map<int,template<class T> > map_; 

通知> >之間的空間。 Pre-C++ 11,>>始終被視爲移位運算符。

除此之外,代碼應該做什麼?如果我沒有記錯的話,你應該申報地圖作爲

std::map<int,message> map_; 

現在,std::map<int,template<class T>> map_;並沒有真正意義,除非這是另一個模板類的成員,在這種情況下,你需要

std::map<int,T> map_; 
+0

downvote的原因是什麼? – 2012-04-03 13:29:58

+0

我如何知道我目前使用哪個編譯器?有沒有我需要運行的任何命令?順便說一句我使用代碼塊作爲一個IDE,其中包括MinGW的GCC編譯器和GDB調試器。 – Glolita 2012-04-03 15:21:11

-1
define KEYINT_MAP(T) std::map<int, T> 
KEYINT_MAP(class) map;