Вопрос

I'm about to compile a pretty easy 'Hello, world' using libconfig. But when I compile such code:

#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;
}

I have this error:

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>]
Это было полезно?

Решение

According to Chapter 4 of the documentation, on page 19, lookup returns a Setting&, not a string.

Now, according to page 20, Setting has a bunch of implicit conversions to various types, including std::string. Here, the conversion to std::string is ambiguous in the presence of the conversion to const char*, since std::string has constructors accepting both with equal rank.

This problem is actually explicitly described on page 21, wherein resolving the ambiguity with an explicit conversion (or "cast") is suggested, or the use of the member c_str() rather than of the conversion operators:

target = cfg.lookup("target").c_str();
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top