簡體   English   中英

編譯錯誤,以迭代器作為補充的C ++模板化函數

[英]compilation error C++ templated function with iterators as arugments

我以為我已經開始了解C ++了。

然后我寫了我以為我們是非常簡單的模板化函數,突然之間似乎沒有任何意義。 編譯器似乎都不喜歡我定義了模板化函數的事實,這似乎有些瘋狂。 它是單個編譯單元,因此我不確定它會抱怨什么。

#include <vector>
#include <iostream>

typedef std::vector<int> int_vec_type;

template <typename Type>
bool print_vec(Type::const_iterator itr, const Type::const_iterator end)
{
    for (; itr != end; ++itr) {
        std::cout << *itr << std::endl;
    }

    return true;
}

int
main()
{
    int_vec_type ivec;

    ivec.push_back(0);
    ivec.push_back(1);
    ivec.push_back(2);

    print_vec(ivec.begin(), ivec.end());

    return 0;
}

這些是編譯錯誤:

tia.cc:7:22:錯誤:'bool print_vec'的模板聲明

tia.cc:7:37:錯誤:在'itr'之前預期為')'

tia.cc:7:42:錯誤:“ const”之前的預期主表達式

tia.cc:在函數'int main()'中:

tia.cc:25:39:錯誤:未在此范圍內聲明'print_vec'

提前致謝。

容器的類型不能從迭代器的類型推導出。 您可以將模板簡單地轉換為:

template <typename Iterator>
bool print_vec(Iterator itr, const Iterator end)
{
    for (; itr != end; ++itr) {
        std::cout << *itr << std::endl;
    }

    return true;
}

第一個問題:您尚未使用typename 無論類型取決於模板參數,都必須在類型typename加上typename

其次,編譯器無法推斷type 它只能看到ivec.begin()的類型,並且不知道其他任何可能將其作為typedef的類型。 您只能直接采用const_iterator您不能采用T::const_iterator無論如何都必須顯式傳遞T

最好的解決方案是使用迭代器類型作為模板,因為不能從函數參數推導出容器的類型:

template <typename Iterator>
bool print_vec(Iterator itr, Iterator end) { .... }

暫無
暫無

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

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