Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the std container have a generic way of inserting into any container?

What I'm currently trying to do is extend the functionality of the C++ std containers. So I have done it like so

template<typename T>
class Queryable : public T
{
public:
    template<typename lambdaFunc>
    Queryable<T>Where(const lambdaFunc& w)
    {
        Queryable<T> whereVecObjects;

        for(auto iterObject = this->cbegin();
            iterObject != this->cend();
            ++iterObject)
        {
            bool add = w(*iterObject);
            if(add == true)
            {
                whereVecObjects.push_back(*iterObject);
            }
        }

        return whereVecObjects;
    }           
};

So what this class does is it accepts an std container in the template and creates a class that inherits from it. It then defines its functions that it wants to extend on the container.

Now this example I have provided above works fine if you are using std::vector like so

int main()
{
    Queryable<std::vector<int>> vecInt;
    vecInt.push_back(1); vecInt.push_back(2); vecInt.push_back(3); vecInt.push_back(4); vecInt.push_back(5); 
    Queryable<std::vector<int>> filteredVec = vecInt.Where([](int i){ return i > 3; } );
    for(auto iter = filteredVec.begin();
        iter != filteredVec.end();
        ++iter)
    {
        std::cout << *iter << ", ";
    }
}

But when I try to use this on a std::map I end up having an issue because of this line whereVecObjects.push_back(*iterObject);

Now I want a generic way to able to do the code above that would work on all the std containers.

Is there such a method?

like image 712
Caesar Avatar asked Oct 03 '22 22:10

Caesar


1 Answers

Try to use insert instead push_back.

whereVecObjects.insert(whereVecObjects.end(), *iterObject);

I think that you need more general Queryable

template <class T, template<class, class...> class Container>
class Queryable
  : public Container<T>
{
  // ...
}

Also I think you need to use Queryable only with containers. See Determine if a type is an STL container at compile time

like image 79
PSyton Avatar answered Oct 07 '22 18:10

PSyton