2017-01-13 23 views
1

假設我有一個std::array<SomeType, N>,我想調用一個函數,它使用迭代器處理std::array中的對象,但不知道容器是否爲std::array使用迭代器執行對象操作的函數

SOMETYPE是具有公共成員函數的doSomething()

例如一個函數可能是一個類:

template<typename Iterator> 
void action(Iterator &beg, Iterator &end) { 
    for (; beg != end; ++beg) 
    beg->doSomething(); 
} 

調用此功能可以通過:

int main() { 
    std::array<SomeType, 10> a; 

    action<std::array<SomeType, 10>::iterator>(a.begin(), a.end()); 
} 

但我想知道這是否是這樣做的方式?尤其是因爲模板可以用於每個類。有沒有辦法將函數限制到SomeType而不讓函數知道容器是std::array

+0

寫入的代碼不會編譯。至少它不是格式良好的C++。 [Demo](http://melpon.org/wandbox/permlink/tw8f7mpNxZTZel9X) –

回答

5
  1. 修復你的代碼:你不應該要求左值參數。事實上,迭代器意味着可以高效地複製。

    template<typename Iterator> 
    void action(Iterator beg, Iterator end) 
    //   ^^^^^^^^^^^^ ^^^^^^^^^^^^ 
    
  2. 設模板實參推演做的工作:

    action(a.begin(), a.end()); 
    
+0

[Demo](http://melpon.org/wandbox/permlink/IftDha8EQMpKdWhi) –

0

注意,標準庫已擁有多項,涵蓋的「做同樣的事情在一些一般情況下的算法範圍在某個容器中「:

#include <array> 
#include <vector> 
#include <algorithm> 
#include <numeric> 
#include <iterator> 

struct SomeType 
{ 
    void doSomething(); 

    SomeType mutatedCopy() const; 

    int someValue() const; 
}; 

int add_value(int i, const SomeType& st) { 
    return i + st.someValue(); 
} 

void call_something(SomeType& st) { st.doSomething(); } 
auto mutate_copy(SomeType const& st) { return st.mutatedCopy(); } 

int main() { 
    std::array<SomeType, 10> a; 
    std::vector<SomeType> b; 

    std::for_each(a.begin(), a.end(), call_something); 
    std::for_each(b.begin(), b.end(), call_something); 

    std::transform(a.begin(), a.end(), a.begin(), mutate_copy); 
    std::transform(b.begin(), b.end(), b.begin(), mutate_copy); 

    auto tot = std::accumulate(a.begin(), a.end(), 0, add_value) 
      + std::accumulate(b.begin(), b.end(), 0, add_value); 

    // you can even transform into dissimilar containers: 

    std::transform(a.begin(), a.end(), std::back_inserter(b), mutate_copy); 

}