簡體   English   中英

c ++模板函數專門化 - 錯誤的模板參數數量?

[英]c++ template function specialization - wrong number of template arguments?

好的,所以我只是在學習模板。 無論如何,我可能(絕對)做錯了什么,但問題是:

我的第一個模板函數聲明如下:

template<typename T>
std::ostream& printFormatted(T const& container, std::ostream& os = std::cout) {
    //...
}

然后我應該為地圖實現一個專門的案例,所以這就是我試圖做的事情:

template<>
std::ostream& printFormatted<std::map<typename key, typename value>>(std::map<typename key, typename value> const& container, std::ostream& os = std::cout) {
    //...
}

我可能在使用我的鍵/值變量時出錯了,不確定,但無論如何,在嘗試編譯時我會收到錯誤消息:

error: wrong number of template arguments (1, should be 4)
error: provided for ‘template<class _Key, class _Tp, class _Compare, class _Allocator> class std::__debug::map’

顯然,我對模板或地圖有些不了解? 有人請幫忙嗎?

假設您對keyvalue使用是安置程序,則無法使用關鍵字typename聲明模板參數。 也就是說, Foo<typename T>總是無效的 - 但不要誤認為Foo<typename T::bar>完全不同。 專業化的語法如下:

// Declare template parameters up front
template<typename Key, typename Value>
std::ostream&
printFormatted<std::map<Key, Value> >(std::map<Key, Value> const& container, std::ostream& os = std::cout);

但這不起作用,因為它是部分特化 ,而且不允許使用功能模板。 使用重載代替:

template<typename Key, typename Value>
std::ostream&
printFormatted(std::map<Key, Value> const& container, std::ostream& os = std::cout);

與一般模板相比,這種重載將是首選。

你所做的不是完全專業化,而是部分專業化,因為你仍然有一個模板,只有一個更專業的模板。 但是,您不能部分專門化函數,因此我們只提供一個新的重載。 對於std::map ,您需要四個模板參數(正如錯誤消息有用地告訴您):

template <typename K, typename V, typename Comp, typename Alloc>
std::ostream & printFormatted(const std::map<K,V,Comp,Alloc> & m,
                              std::ostream & o = std::cout)
{
  // ...
}

這個答案與C ++ 11無關

如果您使用的是pre-c ++ 11編譯器,則在關閉嵌套模板時不能使用>> 你需要在> s之間留一個空格。

C ++將>>視為與>不同的標記,並且編譯器不會使用它來關閉模板。 您需要一個空格,以便編譯器看到>后跟一個>

以下更有可能奏效:

template<>
std::ostream& printFormatted<std::map<typename key, typename value> >(std::map<typename         key, typename value> const& container, std::ostream& os = std::cout) {
    //...
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM