"Concepts" in C ++

    Good day to all.

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

    And to do this without using inheritance from the base class.
    How to do this, read under the cut.

    The main difficulty that I encountered was creating a VectorWrapper type that would have only one template argument (the type of the stored value), but could be created from anything that has a specific set of methods. In my example, these are operator [] and size (). After some time of thought, a design was born that uses the capabilities of the C ++ 11 standard.

    template 
    class VectorWrapper
    {
    public:
        template 
        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 _getter;
        ::std::function _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, in this wrapper, you can wrap anything you want with the size () and operator [] methods.

    I don’t know if it can be used somewhere in real life, I solved my problem, which I wanted to solve in this way before I came up with all this disgrace. There is also a suspicion that if you use such classes everywhere, you can greatly degrade performance.

    Well, purely out of curiosity, the question for the hawkers is whether it is possible to do this without resorting to the help of lambdas and C ++ 11?

    Also popular now: