4

I was trying to create a pair of id and object like this:

 #include <iostream>
  #include <utility>
  #include <functional>

  struct num{

      double x;
      double y;

  };


  int main(){

      auto tmp = std::make_pair(1, {1.0, 2.0});

 }

I get error as error: no matching function for call to 'make_pair(int, <brace-enclosed initializer list>)'

Is there a proper way to create pair of id and object?

3
  • 7
    How is the compiler supposed to guess that {1.0, 2.0} should be a num? Commented Dec 21, 2016 at 19:40
  • 1
    What type would you expect to be deduced automatically for auto tmp?? Your struct is completely unrelated (not introduced at all). Commented Dec 21, 2016 at 19:41
  • @NathanOliver good point :) Commented Dec 21, 2016 at 19:43

1 Answer 1

8

No, This is how you should create your pair:

auto tmp = std::make_pair(1, num{1.0, 2.0});

Or alternatively (as @StoryTeller mentioned):

std::pair<int,num> tmp {1, {1.0, 2.0}};

Now, in both cases, the compiler has a clue that {1.0, 2.0} is meant to be an initializer for the num.

Sign up to request clarification or add additional context in comments.

6 Comments

Personally, if naming the types is already a must, I prefer to shorten the line by simply writing std::pair<int,num> temp{1, {1.0, 2.0}};
Never specify template arguments when using make_pair, just use the pair constructor in that case
@Praetorian may I ask why ?
@solti For one, it's less typing. And then there are cases like this where things won't compile int i = 1; auto tmp = std::make_pair<int,num>(i, {1.0, 2.0}); because of how make_pair is defined. Quoting STL - Don't help the compiler
@Praetorian Thank you very much for mentioning the video
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.