我有这个最小的测试用例:
#include <string>
#include <iostream>
#include <boost/format.hpp>
class LogInterface
{
public:
virtual void log(int level, std::string message) const = 0;
virtual void log(int level, boost::format format) const
{
log(level, format.str());
}
protected:
const int TRACE = 60;
const int DEBUG = 50;
const int INFO = 40;
const int WARN = 30;
const int ERROR = 20;
const int FATAL = 10;
};
class Test : public LogInterface
{
public:
Test()
{
log(INFO, "hello");
log(INFO, boost::format("hello %s") % "world");
}
virtual void log(int level, std::string message) const override
{
std::cout << "LOGGER: " << message << std::endl;
}
};
int main()
{
Test test;
return 0;
}
方法void LogInterface::log(int level, boost::format format) const
是直接将boost::format
传递给LogInterface::log
的便利超载。
问题是Test::Test()
没有解决,导致此错误:
logger_test.cpp:30:19: error: no viable conversion from 'boost::basic_format<char, std::__1::char_traits<char>, std::__1::allocator<char> >' to
'std::string' (aka 'basic_string<char, char_traits<char>, allocator<char> >')
log(INFO, boost::format("hello %s") % "world");
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/usr/bin/../include/c++/v1/string:1349:5: note: candidate constructor not viable: no known conversion from 'boost::basic_format<char,
std::__1::char_traits<char>, std::__1::allocator<char> >' to 'const std::__1::basic_string<char> &' for 1st argument
basic_string(const basic_string& __str);
^
/usr/bin/../include/c++/v1/string:1354:5: note: candidate constructor not viable: no known conversion from 'boost::basic_format<char,
std::__1::char_traits<char>, std::__1::allocator<char> >' to 'std::__1::basic_string<char> &&' for 1st argument
basic_string(basic_string&& __str)
^
/usr/bin/../include/c++/v1/string:1364:31: note: candidate constructor not viable: no known conversion from
'boost::basic_format<char, std::__1::char_traits<char>, std::__1::allocator<char> >' to 'const value_type *' (aka 'const char *') for 1st argument
_LIBCPP_INLINE_VISIBILITY basic_string(const value_type* __s);
^
/usr/bin/../include/c++/v1/string:1385:5: note: candidate constructor not viable: no known conversion from 'boost::basic_format<char,
std::__1::char_traits<char>, std::__1::allocator<char> >' to 'initializer_list<value_type>' (aka 'initializer_list<char>') for 1st argument
basic_string(initializer_list<value_type> __il);
^
logger_test.cpp:33:45: note: passing argument to parameter 'message' here
virtual void log(int level, std::string message) const override
^
1 error generated.