I have this function that converts an integer to a std::string:
std::string intToStr(const int n) {
stringstream ss;
ss << n;
return ss.str();
}
It's worked well so far, but now I'm trying to construct a string to put into a std::pair, and I'm having some trouble.
Given an integer variable hp
and a function that returns an integer int maxHP()
, I want to construct a string that looks like this: "5/10"
(if hp
is 5 and maxHP
returns 10).
here's my attempt:
string ratio = intToStr(hp) + "/" + intToStr(maxHP());
return pair<string, OtherType>(ratio, someOtherType);
Compiling with g++, it fails with this error:
src/Stats.cpp:231: error: no matching function for call to
‘std::pair<std::basic_string<char, std::char_traits<char>, std::allocator<char> >,
TCODColor>::pair(<unresolved overloaded function type>, const TCODColor&)’
/usr/include/c++/4.4/bits/stl_pair.h:92: note: candidates are: std::pair<_T1,
_T2>::pair(std::pair<_T1, _T2>&&) [with _T1 = std::basic_string<char,
std::char_traits<char>, std::allocator<char> >, _T2 = TCODColor]
/usr/include/c++/4.4/bits/stl_pair.h:83: note: std::pair<_T1,
_T2>::pair(const _T1&, const _T2&) [with _T1 = std::basic_string<char,
std::char_traits<char>, std::allocator<char> >, _T2 = TCODColor]
/usr/include/c++/4.4/bits/stl_pair.h:79: note: std::pair<_T1,
_T2>::pair() [with _T1 = std::basic_string<char, std::char_traits<char>,
std::allocator<char> >, _T2 = TCODColor]
/usr/include/c++/4.4/bits/stl_pair.h:68: note:
std::pair<std::basic_string<char, std::char_traits<char>, std::allocator<char> >,
TCODColor>::pair(const std::pair<std::basic_string<char, std::char_traits<char>,
std::allocator<char> >, TCODColor>&)
so std::pair doesn't like my string. I've confirmed that it's not OtherType
causing the problem, because I have another pair constructor that compiles fine:
pair<string, OtherType>("astring", someOtherType);
Anyone see how I can fix this?
Fixed it, though the answer was odd. My problem was that somehow ratio wasn't getting defined, but g++ didn't tell me about it. Changing my code to use make_pair
as GMan suggested suddenly made it tell me. Anyone know why that would happen?
Here's more of the function:
if(verbose)
string ratio = intToStr(hp) + "/" + intToStr(maxHP());
if(div > 1.0f) {
if(verbose) return pair<string, OtherType>(ratio, someOtherType); // doesn't compile
else return pair<string, OtherType("astring", someOtherType); // compiles
}
here's the fixed code:
string ratio = intToStr(hp) + "/" + intToStr(maxHP());
if(div > 1.0f) {
if(verbose) return make_pair(ratio, someOtherType); // compiles now
else return make_pair("astring", someOtherType); // compiles
}