我将使用libconfig编译一个非常简单的“Hello,world”。但是当我编译这样的代码时:
#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>]
最佳答案
根据Chapter 4 of the documentation(在第19页上),lookup
返回Setting&
,而不是字符串。
现在,根据第20页,Setting
具有大量隐式转换为各种类型的转换,包括std::string
。在此,在存在std::string
的情况下,向const char*
的转换是不明确的,因为std::string
的构造函数接受同等等级的两者。
实际上在第21页上明确描述了此问题,其中建议通过显式转换(或“cast”)解决歧义,或者建议使用成员c_str()
而不是转换运算符:
target = cfg.lookup("target").c_str();
关于c++ - C++ libconfig模棱两可的重载,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20744712/