1

我有一个将整数转换为 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
}
4

3 回答 3

4

失败的原因:

if(verbose) 
    string ratio = intToStr(hp) + "/" + intToStr(maxHP());

// the block of the if is now over, so any variables defined in it
// are no longer in scope

是变量的范围仅限于定义它的块。

于 2010-07-22T22:25:37.327 回答
1

Here's how I would fix your code:

if (div > 1.0f)
{
    string str = verbose ? intToStr(hp) + "/" + intToStr(maxHP()) : "astring";
    return make_pair(str, someOtherType); 
}

A little more concise. Also, your formatting could be made a bit more generic.

于 2010-07-22T22:36:02.827 回答
0

看起来这可能是一个const问题。查看它在错误中报告的重载:

  • pair(std::pair<_T1, _T2>&&)
  • pair(const _T1&, const _T2&)

所以看起来它正在期待const参数。

于 2010-07-22T21:59:50.793 回答