mardi 1 janvier 2019

How to get template function to use back_inserter over inserter when appropriate

How do I create a function that adds the contents of one collection to another, using std::back_inserter() if possible for efficiency? I don't see an obvious trait for push_back() and I'm not an expert with std::enable_if, but I'm hoping some combination will achieve the effect of the following:

// IF HAS_PUSH_BACK:
template<typename CIn, typename COut>
void addAll(CIn && from, COut && to) {
    std::copy(std::begin(from), std::end(from), std::back_inserter(to));
}

// IF ! HAS_PUSH_BACK:
template<typename CIn, typename COut>
void addAll(CIn && from, COut && to) {
    std::copy(std::begin(from), std::end(from), std::inserter(to, to.begin()));
}

Aucun commentaire:

Enregistrer un commentaire