dimanche 3 novembre 2019

How to implement a function that accepts any container type?

I want to implement a funtion that takes std::vector or std::array as argument. How can the parameter list abstract from the container type?

See this example:

// how to implement this?
bool checkUniformity(container_type container)
{
    for(size_t i = 1; i < container.size(); i++)
    {
        const auto& o1 = container[i-1];
        const auto& o2 = container[i];

        if(!o1.isUniform(o2))
            return false;
    }

    return true;
}

struct Foo
{
    bool isUniform(const Foo& other);
}

// I want to call it in both ways:
std::vector<Foo> vec;
std::Array<Foo> arr;

bool b1 = checkUniformity(vec);
bool b2 = checkUniformity(arr);

What is the best and most readable way to do this?

Any suggestions for code improvement (style, design) are welcome as well.

Aucun commentaire:

Enregistrer un commentaire