C++ codecvt 不是 std 标头吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15615136/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 19:33:16  来源:igfitidea点击:

Is codecvt not a std header?

c++c++11

提问by user841550

This code compiles with Visual C++ 11 and runs as expected on Windows 7 but fails to compile using either MinGW 4.7.0 on Windows 7 or gcc 4.8.0 on Linux. Compiling with -std=c++11flag

此代码使用 Visual C++ 11 编译并在 Windows 7 上按预期运行,但无法使用 Windows 7 上的 MinGW 4.7.0 或 Linux 上的 gcc 4.8.0 进行编译。用-std=c++11标志编译

#include <codecvt>
#include <string>

// convert UTF-8 string to wstring
std::wstring utf8_to_wstring (const std::string& str)
{
    std::wstring_convert<std::codecvt_utf8<wchar_t>> myconv;
    return myconv.from_bytes(str);
}

// convert wstring to UTF-8 string
std::string wstring_to_utf8 (const std::wstring& str)
{
    std::wstring_convert<std::codecvt_utf8<wchar_t>> myconv;
    return myconv.to_bytes(str);
}

Error:

错误:

codecvt: No such file or directory.

codecvt:没有这样的文件或目录。

采纳答案by user841550

The reason why GCC rejects this code is simple: libstdc++ doesn't support <codecvt>yet.

GCC 拒绝此代码的原因很简单:libstdc++ 尚不支持<codecvt>

The C++11 support status pageconfirms this:

C ++ 11的支持状态页面证实了这一点:

22.5 Standard code conversion facets N

22.5 标准代码转换方面 N

回答by lderache

The question was asked almost 3 years ago and I was surprised that I am also having same issue using Ubuntu 14.04 with fresh updates.

这个问题是在大约 3 年前提出的,我很惊讶我在使用 Ubuntu 14.04 和最新更新时也遇到了同样的问题。

Second surprise, the link provided by @Fanael shows now:

第二个惊喜,@Fanael 提供的链接现在显示:

22.5 Standard code conversion facets Y

22.5 标准代码转换方面Y

So I searched which version of GCC would fully implement C++11. Turns out that full support was added in GCC 5:

所以我搜索了哪个版本的 GCC 会完全实现 C++11。事实证明,在 GCC 5 中添加了全面支持:

https://gcc.gnu.org/gcc-5/changes.html

https://gcc.gnu.org/gcc-5/changes.html

Full support for C++11, including the following new features:

...

locale facets for Unicode conversion;

...

完全支持 C++11,包括以下新特性:

...

Unicode 转换的语言环境方面;

...

I would have been happy to put a comment on the answer if I had enough reputation :)

如果我有足够的声誉,我很乐意对答案发表评论:)

回答by jotrocken

A workaround using Boost.Locale:

使用Boost.Locale的解决方法:

#include <boost/locale/encoding_utf.hpp>
#include <string>

using boost::locale::conv::utf_to_utf;

std::wstring utf8_to_wstring(const std::string& str)
{
    return utf_to_utf<wchar_t>(str.c_str(), str.c_str() + str.size());
}

std::string wstring_to_utf8(const std::wstring& str)
{
    return utf_to_utf<char>(str.c_str(), str.c_str() + str.size());
}  

回答by Maks

It works on Ubuntu 14.04 with gcc 5.3.

它适用于带有 gcc 5.3 的 Ubuntu 14.04。