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.