2013-07-21 43 views
1

我期待在使用boost ::系列化,並嘗試使用上http://www.ocoudert.com給出一個字符串幫手它具有界面引用一個const char *,錯誤C2664:

SerializeCStringHelper(char*& s) : s_(s) {} 
SerializeCStringHelper(const char*& s) : s_(const_cast<char*&>(s)) {} 

我嘗試使用這個助手在下面的代碼(getName()返回一個的std :: string)

bool MyUtilities::saveSerialLibraryToFile(const string& fileName, const MyLibrary& lib) 
{ 
    bool saved = false; 
    ofstream out(fileName, ios::app); 
    if(out.is_open()) 
    { 
     boost::archive::text_oarchive ar(out); 
     const char* str = lib.getName().c_str(); 
     SerializeCStringHelper helper(str); 
//  SerializeCStringHelper helper(lib.getName().c_str()); 
     ar & helper; 
     saved=true; 
    } 
    return saved; 
} 

它編譯罰款,但現在如果我更換了與註釋掉的代碼爲const char *海峽和輔助線,我得到的編譯錯誤C2664:無法將參數1從'const char *'轉換爲'char * &'

我的問題是,爲什麼單行,不同於兩個單獨的行?

回答

2

SerializeCStringHelper helper(lib.getName().c_str());

此行試圖通過臨時到的SerializeCStringHelper構造方法的問題是不能結合臨時到非const引用。這就是爲什麼SerializeCStringHelper helper(str);有效,因爲str不是臨時對象。

例子:

#include <string> 

void foo(const char*& str) {} 

void bar(const char* const & str) {} 

int main() 
{ 
    std::string s("..."); 
    //foo(s.c_str()); 
    bar(s.c_str()); 

    return 0; 
} 

該代碼將編譯很好,因爲酒吧需要一個const引用,但是如果你取消註釋調用FOO,它將無法編譯因爲FOO需要非const引用。

+0

輝煌,謝謝 –

+1

如果答案有用,您可以接受;) – Borgleader

相關問題