c ++ libconfig模糊重载

1 c++ overloading ambiguous libconfig

我即将使用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;
}
Run Code Online (Sandbox Code Playgroud)

我有这个错误:

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>]
Run Code Online (Sandbox Code Playgroud)

Lig*_*ica 7

根据文档的第4章,在第19页上,lookup返回a Setting&,而不是字符串.

现在,根据第20页,Setting有一堆隐含的转换到各种类型,包括std::string.在这里,转换为std::string存在转换时是不明确的const char*,因为std::string构造函数接受两者具有相等的等级.

这个问题实际上是在第21页中明确描述的,其中建议使用显式转换(或"强制转换")来解决歧义,或者使用成员c_str()而不是转换运算符:

target = cfg.lookup("target").c_str();
Run Code Online (Sandbox Code Playgroud)