📜 ⬆️ ⬇️

"Concepts" in C ++

Good day to all.

Invented and written under the influence of some of Straustrup's publications on the topic of concepts in C ++.
I once wanted something unusual — to make non-sample functions / methods in C ++ take as an argument any object that has a specific set of methods, like this:
void fn(VectorWrapper<int> x) { for (size_t i = 0; i < x.size(); ++i) { doSomething(x[i]); } } ::std::vector<int> sv; QList<int> qv; OtherSuperVector<int> ov; fn(sv); fn(qv); fn(ov); 

And do it without using inheritance from the base class.
How it can be done, read under the cut.

The main difficulty I encountered was creating a VectorWrapper type that would have only one template argument (type of stored value), but could be created from anything that has a certain set of methods. In my example, this is operator [] and size (). After a certain amount of time thinking was born about a construct that uses the capabilities of the standard C ++ 11.

 template <typename T> class VectorWrapper { public: template <typename C> VectorWrapper(C& container) : _getter([&container](size_t i) -> T& { return container[i]; }), _sizeGetter([&container]() -> size_t { return container.size(); }) { } T& operator[](size_t i) { return _getter(i); } size_t size() { return _sizeGetter(); } private: ::std::function<T&(size_t) > _getter; ::std::function<size_t() > _sizeGetter; }; 

')
As a result, when creating an object of this class, the object passed to the constructor is captured by the lambdas, and the methods of the class itself simply call the stored lambdas, which in turn pull the methods of the captured object.
Now you can wrap anything into this wrapper with the size () and operator [] methods.

I don’t know if this can be used somewhere in real life, I decided to solve my problem in such a way earlier than I had invented this disgrace. There is also a suspicion that if you use these classes everywhere, you can greatly degrade performance.

Well, purely out of curiosity, the question to habrajitel - is it possible to create such a thing without resorting to the help of lambdas and C ++ 11?

Source: https://habr.com/ru/post/151504/


All Articles