Writing a template that can use std :: vector or std :: set

I wrote an asynchronous job queue class that has been working fine for ages. It uses it std::vectoras a base collection for saving tasks, and then processes them later, as you might expect. When I add a task, he does push_backit vector.

I recently decided that I want to plan the template type of the collection that it uses, and the way I wrote it, it should be very simple. Now it is declared this way:

template<typename J, typename CollectionT = std::vector<J>>
class async_jobqueue
{
public:

There is only one catch, for containers with a vector type I want to push things to the end of the collection and call push_back, for containers of type types I want to call insert. How can I make a compilation decision on how to call? Or is there a convenient adapter that I can use?

+5
source share
3 answers

How about overloading insert(iterator, value_type)and calling it using end()? It is available in both cases and should do what you want! Works on std::list!

Actually there is no need for type dispatching.

+3
source

. , insert(), push_back():

#include <utility>

template<typename C, typename T>
auto insert_in_container(C& c, T&& t) ->
    decltype(c.push_back(std::forward<T>(t)), void())
{
    c.push_back(std::forward<T>(t));
}

template<typename C, typename T>
auto insert_in_container(C& c, T&& t) ->
    decltype(c.insert(std::forward<T>(t)), void())
{
    c.insert(std::forward<T>(t));
}

:

#include <set>
#include <vector>
#include <iostream>

int main()
{
    std::set<int> s;
    std::vector<int> v;

    insert_in_container(s, 5);
    insert_in_container(v, 5);

    std::cout << s.size() << " " << v.size();
}

.

+5

concept-lite, , , ++ 14, , :

template<typename J, typename CollectionT = std::vector<J>>
class async_jobqueue
{
  public:

    requires Associative_container<CollectionT>()
    void adding_function(const J& item) {
      // Uses insert
    }

    requires Sequence_container<CollectionT>()
    void adding_function(const J& item) {
      // Uses push_back
    }
};

, (, , ). -lite .

+2

All Articles