2012-05-08 39 views
0

好的模板化的方法,所以我們知道在STL功能,如創建類的STL風格

std::fill(boolContainer.begin(), boolContainer.end(), false); 

我正在用它起一個容器上的方法的類,和我VE意識到我一樣好可能會在上述的非模板版本的示例模板它喜歡是這樣的:

class SomeClass { 
public: 
    // ... 
    int containerMethod(std::vector<int> &v); 
    // ... 
private: 
    // ... 
}; 

而且我的目標,改變成:

class SomeClass { 
public: 
    // ... 
    template <class InputIterator> 
    int containerMethod(const InputIterator &begin, const InputIterator &end); 
    // ... 
private: 
    // ... 
}; 

但是我無法工作了細節的落實:

template <class Iter> int SomeClass::containerMethod 
(const Iter &begin, const Iter&end) { 
    // Here I need to instantiate an iterator for the container. 
    Iter iter; 
    for (iter = begin; iter != end; ++iter) { 
     // This does not seem to work. 
    } 
    return 0; 
} 

所以現在的問題是如何正確地一個實例化一個模板化的迭代,根據方法的模板參數?請注意,我只需要一個輸入迭代器。

+2

如何不起作用?編譯器錯誤,崩潰,別的東西? – jrok

+0

[適用於我](http://ideone.com/NSL6T)。 –

+3

在標準庫中,按值傳遞迭代器也很常見,因爲它們通常是非常輕量級的對象,反正你經常需要它們的副本(就像你在這個例子中用'begin'做的那樣)。 –

回答

5

您的測試用例不完整,所以我必須諮詢我的水晶球。

你已經將你的模板定義放在源代碼文件中,當它應該在頭文件中。

請參閱:Why can templates only be implemented in the header file?

+0

那麼,現在我覺得很愚蠢......這實際上是問題所在。謝謝。 – rwols

+0

我在哪裏可以找到像您的水晶球?最近它非常準確。 – chris