c++ - How can I use a vector wrapper class when enclosed in another vector? -
consider free function third part library expects std::vector
argument: void foo( std::vector<sometype>& );
now, write wrapper around type can add member functions. able use foo()
type, add access function.
class wrapper { private: std::vector<sometype> _data; public: std::vector<sometype>& data() { return _data; } const std::vector<sometype>& data() const { return _data; } //... other stuff };
this way, can still use foo()
:
wrapper a; foo( a.data() );
but consider function, expects vector of vectors of sometype
(edit: , adds elements vector) :
void bar( std::vector<std::vector<sometype>>& );
but datatype have std::vector<wrapper> vec;
is there way use wrapper type call bar()
? want this:
std::vector<wrapper> vec; bar( ??? );
the point want avoid first call bar()
required type, , having copy 1 one elements vector<wrapper>
.
at first, i'd "no", maybe there smart solution ?
edit2: give example, consider following toy implementation bar()
int
root datatype:
void bar( std::vector<std::vector<int>>& vv ) { std::vector<int> v1 = { 1,2,3 }; std::vector<int> v2 = { 4,5,6 }; vv.push_back(v1); vv.push_back(v2); }
[edited after new comments requiring elements added in bar function] possible solution keep std::vector<std::vector<sometype>>
function use , operate on vectoraccessor
object referring real vectors
#include <iostream> #include <vector> struct sometype { int value; sometype(int v) : value(v) {} }; void bar(std::vector<std::vector<sometype>>& par) { std::cout << "bar() - before adding new elements:" << std::endl; (auto& subvec : par) { std::cout << "subvector: {"; (auto& sometypeitem : subvec) { std::cout << sometypeitem.value << " "; } std::cout << "};" << std::endl; } std::vector<sometype> newitem = {32, 33}; par.emplace_back(newitem); } class vectoraccessor { std::vector<std::vector<sometype>>& m_vec; public: vectoraccessor(std::vector<std::vector<sometype>>& v) : m_vec(v) {} template<typename v> void addvector(v&& vec) { static_assert(std::is_same<typename std::remove_reference<v>::type, std::vector<sometype>>::value, "not right type"); m_vec.emplace_back(std::forward<v>(vec)); } std::vector<sometype> accessvector(size_t index) { return m_vec[index]; } }; int main(int argc, char ** argv) { std::vector<std::vector<sometype>> vec; vectoraccessor vacc(vec); // add element through vector accessor std::vector<sometype> firstvector = {42}; firstvector.emplace_back(52); vacc.addvector(firstvector); // call bar , add few elements bar(vec); // access stuff usual wrapper std::cout << "elements added bar:" << std::endl; std::cout << "subvector: {"; (auto& sometypeitem : vacc.accessvector(1)) { std::cout << sometypeitem.value << " "; } std::cout << "};" << std::endl; return 0; }
Comments
Post a Comment