【问题标题】:"to_string" isn't a member of "std"?“to_string”不是“std”的成员?
【发布时间】:2013-10-07 23:45:35
【问题描述】:

好的,我有

tmp.cpp:

#include <string>

int main()
{
    std::to_string(0);
    return 0;
}

但是当我尝试编译时,我得到:

$ g++ tmp.cpp -o tmp
tmp.cpp: In function ‘int main()’:
tmp.cpp:5:5: error: ‘to_string’ is not a member of ‘std’
     std::to_string(0);
     ^

我正在运行 g++ 版本 4.8.1。与我在那里发现的所有其他对该错误的引用不同,我不使用 MinGW,我使用的是 Linux (3.11.2)。

任何想法为什么会发生这种情况?这是标准行为,我做错了什么还是某处有错误?

【问题讨论】:

  • 使用g++ -std=c++11 -o tmp tmp.cc,我得到`error: 'to_string' is not a member of 'std'。 g++ 版本是 4.8.2 。这是回归吗?
  • 嗯,不确定,但它适用于 g++ 4.9.0
  • gcc --version 使用 gcc tdm-2 4.8.1,使用 -std=c++11 编译仍然会产生错误 'to-string' is not member of std
  • 对我来说也一样。使用arm-none-eabi-gcc -std=c++11 我仍然收到错误消息。

标签: c++ linux string c++11 g++


【解决方案1】:

to_string 适用于最新的 C++ 版本,例如版本 11。对于旧版本,您可以尝试使用此函数

#include <string>
#include <sstream>

template <typename T>
std::string ToString(T val)
{
    std::stringstream stream;
    stream << val;
    return stream.str();
}

通过添加模板,您也可以使用任何数据类型。 您必须在此处包含#include&lt;sstream&gt;。

【讨论】:

  • 使用std::ostringstream 会不会更safe,因为我们只想要流的输出?
【解决方案2】:

您可能需要指定 C++ 版本

g++ -std=c++11 tmp.cpp -o tmp

我手头没有 gcc 4.8.1,但在旧版本的 GCC 中, 你可以使用

g++ -std=c++0x tmp.cpp -o tmp

至少 gcc 4.9.2 我相信通过指定也支持部分 C++14

g++ -std=c++1y tmp.cpp -o tmp

更新: gcc 5.3.0(我使用的是cygwin版本)现在支持-std=c++14和-std=c++17。

【讨论】:

  • 在 Debian 8 (Linux 3.14-2-amd64) 上的 Eclipse CDT 中出现此错误。在设置中指定 GCC C++ 编译器来运行命令g++ -std=c++11 解决了我的问题!谢谢!
  • 使用 -std=c++11 编译时,gcc --version tdm-2 4.8.1 中仍然出现错误
  • 我也遇到过这个问题,gcc的标准库(libstdc++)中似乎没有std::to_string,但是LLVM/clang自带的libc++中可以使用class="comcopy">跨度>
  • 你用的是什么版本的gcc,你也可以试试-std=c++1y
猜你喜欢
  • 2020-05-23
  • 2014-11-23
  • 2014-04-06
  • 2012-10-10
相关资源
最近更新 更多