Avoid Conversion from single element vector to primitive type

  • A+

I have a problem with constant single element std::vector when pass through a function. C++ compiler automatically call wrong function when the std::vector variable contain a single element. This is though the policy of C++ design. However is there any explicit method to specify in such a case. Here are the examples of the problems

assume i have two overload functions both have the same name "foo"  void foo(const std::vector<int> A) {          // do vector operator      printf("vector thing"); }   void foo(int a) {      // do integer operator      printf("integer thing") } 

In general case both of these functions are called correctly

foo({1,2,3});    // print do vector thing foo( 3 );        // print do integer thing 

however from c++ rule. when call

foo({5});        // print do integer thing ( I want it to call as vector ) 

one of the methods is to create a variable

std::vector<int> B = { 5 }; 

in order to solve this problem.

I feel this method is a bit clumsy. Is there any method that can void the compiler to treat {5} as 5 and call foo(int a).

note: here is the reference that explain what the problem is c++11 single element vector initialization in a function call


You need another overload, taking std::initializer_list as a parameter:

void foo(std::initializer_list<int> A) {     foo(std::vector<int>(A.begin(), A.end())); } 

If you always call this function by creating vectors directly with {...}, rather than using std::vector variables, then you can remove std::vector overload completely and operate directly on std::initializer_list.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: