2016-11-10 54 views
1

我試圖使用模板來避免在std::vector上執行const和非const範圍時的代碼重複。使用模板實現const範圍

非const版本有效,但const版本沒有。我不知道爲什麼。

test.cpp。與g++ test.cpp編譯:

#include <vector> 
#include <iostream> 
enum Cv { 
    constant, 
    non_constant 
}; 

template <typename T, typename Index, Cv Cv_enum> 
class Vector_range_facade { 
    typedef typename std::conditional < 
      Cv_enum == Cv::constant, 
        const std::vector<T>, std::vector<T> 
    >::type Vec; 
public: 
    typedef typename Vec::iterator Iterator; 
    Vector_range_facade(Vec& vec, const Index start_id, const Index size) 
      : vec_{vec}, 
       it_begin_{vec_.begin() + start_id}, 
       it_end_ {vec_.begin() + start_id + size} 
    {} 
    Iterator& begin() {return it_begin_;} 
    Iterator& end() {return it_end_;} 
private: 
    Vec& vec_; 
    Iterator it_begin_; 
    Iterator it_end_; 
}; 

int main() 
{ 
    std::vector<int> a; 
    a.resize(100); 
    Vector_range_facade<int, int, Cv::constant> range(a,0,10); 
    for (auto x : range) { 
     std::cout << x <<"\n"; 
    } 
} 

回答

3

std::vector::iterator始終計算爲一個非const迭代器的類型,因爲它是內部std::vector定義的typedef無法知道,如果它被稱爲上const或非const實例。

您需要有條件地選擇std::vector::iteratorstd::vector::const_iterator之間的迭代器類型。例如:

typedef typename std::conditional < 
     Cv_enum == Cv::constant, 
     typename std::vector<T>::const_iterator, 
     typename std::vector<T>::iterator 
>::type Iterator; 

on wandbox