I have a function func
which is overloaded to take either a std::vector<Obj>
argument or a Obj
argument.
#include <vector>
#include <iostream>
class Obj {
int a = 6;
};
void func(const std::vector<Obj>& a) {
std::cout << "here" << std::endl;
}
void func(const Obj& a) {
std::cout << "there" << std::endl;
}
int main() {
Obj obj, obj2;
func({obj});
func({obj, obj2});
}
Actual output:
there
here
Expected output:
here
here
It seems {obj}
doesn't initialize a vector, but rather an object. I guess there is some priority order when it comes to which type it initializes. How do I control it precisely?
(Examples compiled with g++ (Ubuntu 8.3.0-6ubuntu1) 8.3.0.)
I found a possible duplicate (c++11 single element vector initialization in a function call), although my question remains unanswered:
I understand that {obj}
can resolve to an object rather a vector of a single element and the former takes priority. But is there a way to use {}
to create a single item vector (so that foo
resolves to the std::vector
overload)? I could create a vector explicitly but {}
seems nicer.
As mentioned in the linked question duplicate (the original) there is no way to force the resolution in favour of the overload taking std::initializer_list
.
The original signatures (using int
to simplify):
void func(const std::vector<int> &a);
void func(const int &a);
Since I have encountered this many times I typically do this:
func(std::vector<int>{10});
I am not aware of any shorter way of doing this because using actual type std::initializer_list
that would do the same is even more verbose. But on the birght side it at least makes what you are doing perfectly clear since {10}
is really ambiguous if not accompanied with the type.
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