Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
197 views
in Technique[技术] by (71.8m points)

c++ - Weird compiler error: Cannot convert parameter from 'int' to 'int &&'

What on earth is going on here?
I'm trying to create a pair of an int and a string and I can create the pair if I use "magic values" but can't seem to pass in variables.

std::vector<std::pair<int, std::string> > num_text;

std::string text = "Smeg";
int num = 42;

// Works fine
num_text.push_back(std::make_pair<int, std::string>(42, std::string("Smeg")));  

// Cannot convert parameter 2 from 'std::string' to 'std::string &&'
num_text.push_back(std::make_pair<int, std::string>(42, text));

// Cannot convert parameter 1 from 'int' to 'int &&'
num_text.push_back(std::make_pair<int, std::string>(num, std::string("Smeg")));

// Cannot convert parameter 1 from 'int' to 'int &&'
num_text.push_back(std::make_pair<int, std::string>(num, text));

// Works fine again
num_text.push_back(std::make_pair<int, std::string>(42, std::string("Smeg")));

I am using VS 2012 and have pasted in some code that was written in VS 2008. Can't imagine that would have anything to do with it but there was no problem in the original (2008) code.

I kind of feel a bit dumb for not being able to workout what is going on here but what can I say, I just don't get it.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Reference says:

template< class T1, class T2 >
std::pair<T1,T2> make_pair( T1 t, T2 u );           (until C++11)

template< class T1, class T2 >
std::pair<V1,V2> make_pair( T1&& t, T2&& u );       (since C++11)

Note that the return type is different. It also says:

The deduced types V1 and V2 are std::decay::type and std::decay::type (the usual type transformations applied to arguments of functions passed by value) unless application of std::decay results in std::reference_wrapper for some type X, in which case the deduced type is X&.

So in fact, since 2008 (I mean Visual C++ 2008), the semantics of the function make_pair has changed. You could either remove the template parameters from std::make_pair and let it deduce the type, or use std::pair's constructor if you need to make pairs of specific type:

num_text.push_back(std::make_pair(num, text));               // deduced type
num_text.push_back(std::pair<int, std::string>(num, text));  // specific type

The reason for the compile error is that you have specified the types to be int (as T1) and std::string (as T2), and therefore the function expects T1 && and T2 &&. See this answer for why that's a problem.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...