2013-12-23 69 views
1

我正在編譯一個非常簡單的'Hello,world'使用libconfig。但是,當我編譯這樣的代碼:C++ libconfig模糊過載

#include <iostream> 
#include <libconfig.h++> 

libconfig::Config cfg; 

std::string target = "World"; 

int main(void) 
{ 
    try 
    { 
     cfg.readFile("greetings.cfg"); 
    } 
    catch (const libconfig::FileIOException &fioex) 
    { 
     std::cerr << "I/O error while reading file." << std::endl; 
     return 1; 
    } 
    catch (const libconfig::ParseException &pex) 
    { 
     std::cerr << pex.getFile() << " " << pex.getLine() 
       << ": " << pex.getError() << std::endl; 
     return 1; 
    } 

    try 
    { 
     target = cfg.lookup("target"); 
    } 
    catch (const libconfig::SettingNotFoundException &nfex) 
    { 
     std::cerr << "No target set in configuration file. Using default." << std::endl; 
    } 

    std::cout << "Hello, " << target << "!" << std::endl; 

    return 0; 
} 

我有這樣的錯誤:

example1.cpp: In function 'int main()': 
example1.cpp:28: error: ambiguous overload for 'operator=' in 'target = cfg.libconfig::Config::lookup(((const char*)"target")) 

/usr/include/c++/4.2/bits/basic_string.h:490: note: candidates are: std::basic_string<_CharT, _Traits, _Alloc>& std::basic_string<_CharT, _Traits, _Alloc>::operator=(const std::basic_string<_CharT, _Traits, _Alloc>&) [with _CharT = char, _Traits = std::char_traits<char>, _Alloc = std::allocator<char>] 
/usr/include/c++/4.2/bits/basic_string.h:498: note:     std::basic_string<_CharT, _Traits, _Alloc>& std::basic_string<_CharT, _Traits, _Alloc>::operator=(const _CharT*) [with _CharT = char, _Traits = std::char_traits<char>, _Alloc = std::allocator<char>] 
/usr/include/c++/4.2/bits/basic_string.h:509: note:     std::basic_string<_CharT, _Traits, _Alloc>& std::basic_string<_CharT, _Traits, _Alloc>::operator=(_CharT) [with _CharT = char, _Traits = std::char_traits<char>, _Alloc = std::allocator<char>] 

回答

7

Chapter 4 of the documentation,第19頁,lookup返回Setting&,而不是一個字符串。

現在,根據第20頁,Setting有許多隱式轉換爲各種類型,包括std::string。這裏,由於std::string的構造函數具有相同的等級,因此在轉換爲const char*時轉換爲std::string是不明確的。

此問題實際上是明確地21頁上所描述的,其中,與顯式轉換分辨歧義(或「轉換」)的建議,或使用該構件c_str()的而不是轉換運算符的:

target = cfg.lookup("target").c_str(); 
+0

它也不會用'target = static_cast (cfg.lookup(「target」));' 'example1.cpp:34:error:調用重載的basic_string(libconfig :: Setting&)'是模棱兩可的 ' – user3129692

+0

c_str()做了詭計,謝謝。 – user3129692