我有一个将整数转换为 std::string 的函数:
std::string intToStr(const int n) {
stringstream ss;
ss << n;
return ss.str();
}
到目前为止它运行良好,但现在我正在尝试构造一个字符串以放入 std::pair,但我遇到了一些麻烦。
给定一个整数变量hp
和一个返回整数的函数int maxHP()
,我想构造一个如下所示的字符串:("5/10"
如果hp
为 5 并maxHP
返回 10)。
这是我的尝试:
string ratio = intToStr(hp) + "/" + intToStr(maxHP());
return pair<string, OtherType>(ratio, someOtherType);
使用 g++ 编译失败,出现以下错误:
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>&)
所以 std::pair 不喜欢我的字符串。我已经确认它不会OtherType
导致问题,因为我有另一个编译好的对构造函数:
pair<string, OtherType>("astring", someOtherType);
任何人都知道我该如何解决这个问题?
修复了它,尽管答案很奇怪。我的问题是,不知何故,比率没有得到定义,但 g++ 没有告诉我这件事。更改我的代码以make_pair
按照 GMan 的建议使用,这突然让我知道了。有谁知道为什么会这样?
这里有更多的功能:
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
}
这是固定代码:
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
}