i trying make generic container hold objects , position:
class vector; template <typename t> class container { public: void insert(const t& t) { insertatposition(t.getposition() ,t); } private: void insertatposition(const vector& v, const t& t); ... } ;
but if users' object position getter not called getposition
?
how can make container generic respect way in container internally obtains position of item?
so far, have considered 3 approaches, none of them ideal:
- add
std::function<const vector& (const t& t)>
membercontainer
.
this clean c++ solution, function going called very , may result in noticeable performance decrease.
add functor object container:
class vector; template <typename t, typename tgetposition> class container { public: container(tgetposition getposition): getposition_(getposition){} void insert(const t& t) { insertatposition(getposition_(t) ,t); } private: void insertatposition(const vector& v, const t& t); tgetposition getposition_; } ;
i can use object generator idiom make possible use lambdas:
template <typename t, typename tgetposition> container<t, tgetposition> makecontainer(tgetposition getter) { return container<t, tgetposition>(getter); } ... auto container = makesimplecontainer<widget>([](const widget& w) { return w.tellmewhereyourpositionmightbe(); });
there no performance overhead, impossible type of such container in contexts. example, not create class take such container parameter, since decltype
not work, because lambdas cannot used in unevaluated contexts.
- use
#define getter getposition
, user changegetposition
whatever likes. there many things wrong approach don't know start.
please, there other way this? did miss anything. guidance welcome!
edit:
regarding solution 2: have no idea how type of container created lambda function. 1 way be:
using tcontainer = decltype(makesimplecontainer<widget>([](const widget& w) { return w.tellmewhereyourpositionmightbe(); });)
but doesn't work, because lambdas cannot used in unevaluated contexts.
reasonably usable option expect context have position_for()
:
template <class t> struct container { size_t insert(t const& x) { insertatposition(position_for(x), x); } }; vector const& position_for(const widget& w) { return ...; } container<widget> c; c.insert(widget());
...but designs container generates key business object not fly well, lookup object 1 need dummy one, may expensive.
Comments
Post a Comment