2013-08-21 185 views
4

虽然下面的代码在Linux上编译,但我无法在Windows上编译它:boost :: filesystem :: path :: native()返回std :: basic_string <wchar_t>而不是std :: basic_string <char>

boost::filesystem::path defaultSaveFilePath(base_directory); 
defaultSaveFilePath = defaultSaveFilePath/"defaultfile.name"; 
const std::string s = defaultSaveFilePath.native(); 
return save(s); 

其中base_directory是一个类的属性,它的类型是std :: string,而函数save只需要一个const std :: string &作为参数。编译器抱怨第三行代码:

错误:从'const string_type {aka const std :: basic_string}'转换为非标量类型'const string {aka const std :: basic_string}'请求“

对于这个软件,我用两个升压1.54(对于某些公共库)和Qt 4.8.4(为使用这个公共库的UI)和我都编译使用MinGW GCC 4.6.2。

如果我的评估是正确的,我会问你:我该如何使std :: stri的Boost返回实例返回实例如果我的Windows Boost构建返回std :: basic_string NG?顺便说一句,有可能吗?

如果我对这个问题做了一个糟糕的评估,我请你提供一些关于如何解决这个问题的见解。

干杯。

回答

5

在Windows上,boost :: filesystem代表原生路径,设计为wchar_t - 请参阅documentation。这非常合理,因为Windows上的路径可以包含非ASCII Unicode字符。你不能改变这种行为。

请注意std::string只是std::basic_string<char>,并且所有本地Windows文件函数都可以接受宽字符路径名(只需调用FooW()而不是Foo())。

+1

谢谢你,这是真的很有帮助。你能提出一种方法来使这个代码更加便携吗?我是否应该将我的字符串声明为文件系统路径作为boost :: filesystem :: path :: string_type贯穿我的代码?这里有什么好的做法? – Ramiro

+2

这取决于你想要对路径做什么。最便携,但限制最多的是坚持'filesystem :: path'并使用boost提供的文件操作和iostream功能。如果你需要更具体的东西,你会失去可移植性,但会获得灵活性。 –

2

how do I make Boost return instances of std::string? BTW, is it possible?

string()wstring()怎么样?

const std::string s = defaultSaveFilePath.string(); 

还有

const std::wstring s = defaultSaveFilePath.wstring(); 
+1

这解决了编译问题,但我想我现在主要关心的是要知道是否有和使用Boost Filesystem路径对象为Linux和Windows编写可移植代码的良好实践。 – Ramiro

2

加速路径具有一个简单的功能设置,让您在 “本机”(即便携式)格式的std :: string。使用make_preferred结合string。这是在Boost支持的不同操作系统之间可移植的,并且还允许您在std::string中工作。

它看起来像这样:

std::string str = (boost::filesystem::path("C:/Tools")/"svn"/"svn.exe").make_preferred().string(); 

或者,从原来的问题修改代码:

boost::filesystem::path defaultSaveFilePath(base_directory); 
defaultSaveFilePath = defaultSaveFilePath/"defaultfile.name"; 
auto p = defaultSaveFilePath.make_preferred(); // convert the path to "preferred" ("native") format. 
const std::string s = p.string(); // return the path as an "std::string" 
return save(s); 
相关问题