簡體   English   中英

stl容器的模板

[英]Template for stl container

Density類的聲明中,我構建了這些成員函數:

class Density {
public:
    template <typename Container>
    void printStream (Container<Point>::iterator lo, Container<Point>::iterator hi);
......
};

在cpp文件中:

template <typename Container>
void Density::printStream (Container<Point>::iterator lo, Container<Point>::iterator hi)
{
...
}

但是在嘗試編譯時會遇到這些錯誤:

src/../include/density.hpp:166:23: error: 'Container' is not a template
src/../include/density.hpp:166:50: error: expected unqualified-id before 'lo'
src/../include/density.hpp:166:50: error: expected ')' before 'lo'
src/../include/density.hpp:166:50: error: expected initializer before 'lo'
src/density.cpp: In member function 'void Density::startAlgorithm()':
src/density.cpp:291:43: error: 'printStream' was not declared in this scope
src/density.cpp: At global scope:
src/density.cpp:327:28: error: 'Container' is not a template
src/density.cpp:327:55: error: expected unqualified-id before 'lo'
src/density.cpp:327:55: error: expected ')' before 'lo'
src/density.cpp:327:55: error: expected initializer before 'lo'

我應該修改什么? 而且,為什么,因為我想了解這個問題。

NB。 如評論所述,您可能不了解使用模板對頭文件中模板定義的可見性的影響。 讓我指出條目: 為什么模板只能在頭文件中實現?


使用模板模板參數

template <template <typename...> class Container>
void Density::printStream ()
{
    typename Container<Point>::iterator lo;
    typename Container<Point>::iterator hi;
}

你想要做什么,在我看來是不可能的,因為迭代器參數是不可導入的上下文,所以你最終會明確地指定容器類型:

   density_instance.printStream<std::vector>(it1, it2);

但請注意,這並不是一個真正的問題,因為您可能並不真正關心容器的精確類型。 慣用的方式是:

template <typename It>
    void printStream (It lo, It hi);  

您可以隨意撥打電話

std::vector<int> v { 1,2,3 };
density_instance.printStream(begin(v), end(v));

但也有一個非類容器,因為迭代器是重要的:

const int a[] = { 1,2,3 };
density_instance.printStream(std::begin(a), std::end(b));

暫無
暫無

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

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