Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining a function so that it can accept either a list or a vector

Tags:

c++

stl

I have a function which needs to receive either an std::list or an std::vector of MyClass * objects and do a bunch of processing depending on what's inside. I don't want to duplicate the function body.

I only need to use these objects to iterate over them and do some read-only checks.

I had thought of passing .begin() and .end() iterators directly, but that doesn't seem pretty at all.

Is there a better way to get around this, currently I have the following solution (which creates another list out of the vector being passed, which is hardly ideal either).

void process(std::list<MyClass*> input)
{
    //A lot of processing
    BOOST_FOREACH(MyClass* itMyClass, input)
    {
        //some checks, creating new list based on the checks      
    }
    //A lot of processing
}
void process(std::vector<MyClass*> input)
{
    process(std::list<MyClass*>(input.begin(), input.end()));
}

EDIT:

It seems that many people are suggesting to go for begin() and end() after all, I've made it work in a way similar to the example below. Thanks for your help.

//This one is private
template <typename Iterator>
void process(Iterator begin, Iterator end)
{
    //A lot of processing
    for (; begin != end; ++begin) 
    {
        //some checks, creating new list based on the checks
    }
    //A lot of processing
}
void process(std::list<MyClass*> input)
{
    process(input.begin(), input.end());
}
void process(std::vector<MyClass*> input)
{
    process(input.begin(), input.end());
}
like image 828
Yu Ko Avatar asked Oct 28 '25 05:10

Yu Ko


1 Answers

You can use a function template for that:

template<class ListOrVector>
void process(ListOrVector const& input) {
    //your code
}

//You can also use a template template parameter
template<template<class My, class Alloc = std::allocator<My>> class ListOrVector>
void process(ListOrVector<MyClass*, Alloc> const& input) { ... }

Note that I take the ListOrVector by const reference (The const &). This will prevent a copy.

EDIT

I have fixed the second example. The classbefore the ListOrVector was missing and the allocator is std::allocator<My by default.

like image 165
Kilian Avatar answered Oct 30 '25 20:10

Kilian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!