codecvt不是标准头文件吗?

45

这段代码在 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);
}

错误:

codecvt:没有这个文件或目录。


1
请注意,已经实现了C++11 codecvt的编译器(例如MSVC),很可能会在这篇C++17论文中将其弃用:http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2017/p0618r0.html。除非论文中的“其他方向”具有优先权。 - vulcan raven
4个回答

31
GCC拒绝这段代码的原因很简单:libstdc++尚不支持。

C++11 support status page证实了这一点:

22.5标准代码转换facet N


看起来很正常,因为标准库中没有 <codecvt> 这个文件,所以它不支持。 - James Kanze
12
@JamesKanze 说有一个地方。你认为 "22.5" 指的是什么?它是定义 <codecvt> 的部分。 - user784668
又是C++11的一个特性,我看到了。(更有意义的做法是简单地定义名称并使用现有的工具。) - James Kanze
1
嗨,我仍在寻找解决方法。有人有什么建议吗? - Swtsvn
@Hugues 和 Swtsvn:我曾经遇到过同样的问题,并使用 boost.locale 解决了它:请看下面的答案。 - jotrocken

23

这个问题提出了将近3年,我很惊讶地发现我也在使用更新的Ubuntu 14.04时遇到了同样的问题。

第二个令人惊讶的是,@Fanael提供的链接现在显示如下:

22.5标准代码转换facet Y

因此,我搜索了哪个版本的GCC能够完全实现C++11。结果发现完全支持C++11的GCC版本为5:

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

完全支持C++11,包括以下新功能:

...

用于Unicode转换的locale facet;

...

如果我有足够的声望,我会很高兴在回答中发表评论的:)


22

使用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());
}  

你知道任何不需要使用boost的解决方案吗? - John Jiang
除了这个帖子中的其他答案,我很抱歉没有更好的解决方案。我希望你有一个最近的标准库实现,不再需要这个解决方法。 - jotrocken
只有Gcc4.8.5适用于Bazel。 - John Jiang
@Nikos 是的,但我们只有4.8.5 :-( - John Jiang

2

这在Ubuntu 14.04上使用gcc 5.3是有效的。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接