簡體   English   中英

C ++將模板類型作為參數傳遞給錯誤

[英]C++ passing template type as argument gives error

我有以下代碼,問題是當我嘗試將basic_string類型傳遞給writeContainer函數時,它給我帶來了錯誤,它將類型Cont讀取為std :: _ St​​ring_val <std :: _ Simple_types>,因此它給了我錯誤,就像沒有大小( )方法,並且每個循環都沒有end()或begin()方法。

不錯的是,當我使用vector時,即使它們是同一概念,它也能正常工作! 任何幫助表示贊賞

template< template<typename> class Cont, typename T >
void writeContainer(Stream& stream, const Cont<T>& outValue) {
    stream << (int32_t)outValue.size(); 
    for (auto& v : outValue) {
        stream << v;
    }
}

template<typename T> 
Stream& operator<<(Stream& stream, const basic_string<T>& outValue) {
    writeContainer(stream, outValue); 
    return stream; 
}

我得到的錯誤,我使用VS2013

error C2039: 'size' : is not a member of 'std::_String_val<std::_Simple_types<char>>'
see reference to function template instantiation 'void  writeContainer<std::_String_val,std::_Simple_types<char>>(Stream &,const std::_String_val<std::_Simple_types<char>> &)' being compiled
see reference to function template instantiation 'Stream &operator <<<char>(Stream &,const std::basic_string<char,std::char_traits<char>,std::allocator<char>> &)' being compiled
error C3312: no callable 'begin' function found for type 'const std::_String_val<std::_Simple_types<char>>'
error C3312: no callable 'end' function found for type 'const std::_String_val<std::_Simple_types<char>>'
error C2065: 'v' : undeclared identifier

對於模板模板參數,參數必須是具有完全相同數量的參數的類模板-計算具有默認值的參數。 因此,即使std::vector可以用一個參數實例化,它也是一個兩參數模板(第二個參數具有默認值),並且不能作為Cont的參數。 同樣, std::basic_string是一個三參數模板。

您的示例中發生的事情是這樣的。 在此特定實現中, std::basic_string從名為_String_val的內部類_String_val ,通過不幸的巧合,該類恰好是一個單參數模板。 因此推斷Cont_String_val ,但是實例化失敗,因為_String_val沒有名為size的方法(該方法由basic_string本身實現)。

盡管您的說法相反,但出於完全相同的原因,當使用std::vector代替std::basic_string時,出現了類似的錯誤

現在,沒有理由將Cont為模板模板參數(並且有充分的理由不這樣做-它將無法工作)。 將其設為普通類型參數,否則讓函數使用一對迭代器。 遵循以下原則:

template<typename Cont>
void writeContainer(Stream& stream, const Cont& outValue);

// or

template<typename Iter>
void writeRange(Stream& stream, Iter first, Iter last);

暫無
暫無

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

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