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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With