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";
}
}