2013-08-21 106 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); 
相關問題