0

Linux compilation error - cannot convert type ‘string’ to type ‘string&&’, when inserting into a map containing string. The same is building fine on Windows. My use case:

void insertIf(std::string str1, int value, std::map<std::string,int> &myMap) const
{
    if(value == 1)
    {
        myMap.insert(std::make_pair<std::string, int>(str1, value));       
    }
}
2
  • 1
    May we have a minimal reproducible example? Commented Jan 4, 2017 at 17:37
  • 1
    Typo? arg1.insert(std::make_pair<std::string,int>(str1,int1)); <-- )) Commented Jan 4, 2017 at 17:38

1 Answer 1

1

That's because std::make_pair takes forwarding reference as parameter. You should use std::make_pair with a deducing context and the constructor of std::pair when you want to specify template parameter explicitly.

Here's are your choices :

make_pair:

void insertIf(std::string str1, int value, std::map<std::string,int>& myMap) {
    if(value == 1 {
        myMap.insert(std::make_pair(str1, value));
    }
}

pair constructor

void insertIf(std::string str1, int value, std::map<std::string,int>& myMap) {
    if(value == 1 {
        myMap.insert(std::pair<std::string, int>(str1, value));
    }
}

Even better, emplace:

void insertIf(std::string str1, int value, std::map<std::string,int>& myMap) {
    if(value == 1 {
        myMap.emplace(str1, value);
    }
}

If you really want to use std::make_pair with explicit parameters, you can specify the value category in the template parameter but I advise you to not do this, it kinda defeats the whole purpose of std::make_pair :

void insertIf(std::string str1, int value, std::map<std::string,int>& myMap) {
    if(value == 1 {
        myMap.insert(std::make_pair<std::string&, int&>(str1, value));
    }
}

Edit: it worked on Windows because you must use an outdated version of VS, which don't support forwarding reference yet.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.