Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::vector insert without knowing the type of the elements

Tags:

c++

c++11

vector

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?

like image 815
Lajos Nagy Avatar asked Dec 24 '22 17:12

Lajos Nagy


1 Answers

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.

like image 103
T.C. Avatar answered Mar 07 '23 00:03

T.C.