1

我即将使用 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>]
4

1 回答 1

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();
于 2013-12-23T13:49:41.330 回答