std::vector insert without knowing the type of the

2019-06-25 09:24发布

问题:

Suppose I have a templated function that takes various kinds of vectors (but for various reasons I can't mention this in the template parameter). Here's what I'm trying to do: insert a new, default constructed element at a specific spot, without knowing its type:

template <typename T>
void foo(T* v) {
  v->insert(v->begin() + 5, decltype(v->at(0))());
}

This doesn't work, but gives you an idea of what I'm trying to do. I also tried to use value_type from std::vector but I ran into problems there as well. Any ideas how to solve this problem?

回答1:

Sidestep the whole "name the type" business:

v->emplace(v->begin() + 5);

or

v->insert(v->begin() + 5, {});

Your current version doesn't work because decltype(v->at(0)) is a reference type. value_type should work if you use it correctly, but without seeing what you are doing I can't say what's wrong with it.



回答2:

If you know v is always a std::vector of some element type, then just type it that way to begin with, so T is the element type, not the vector type:

template <typename T>
void foo(std::vector<T>* v) {
  v->insert(v->begin() + 5, T());
}

That also ensures that v->insert() and v->begin() + 5 are valid statements. You original code allowed anything to be passed for v, so there was no guarantee that v->insert() and v->begin() exist, or that begin() returns a random-access iterator that accepts + 5.



标签: c++ c++11 vector