c++ - Implementing const range with template -
i tried use template avoid code duplication in implementation of const , non-const range on std::vector
.
the non-const version works, const version not. don't know why.
test.cpp. compile 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); (auto x : range) { std::cout << x <<"\n"; } }
std::vector::iterator
evaluates type of non-const
iterator, typedef
defined inside std::vector
cannot know if it's being called on const
or non-const
instance.
you need conditionally select iterator type, between std::vector::iterator
, std::vector::const_iterator
. example:
typedef typename std::conditional < cv_enum == cv::constant, typename std::vector<t>::const_iterator, typename std::vector<t>::iterator >::type iterator;
Comments
Post a Comment