1

我有以下界面

virtual void send_command( const std::string& command, const std::string& key, const std::string& value, bool pipeline = true );    
virtual void send_command( const std::string& command, const std::string& key, bool pipeline = true );
virtual void send_command( const std::string& command, bool pipeline = true );

这在一个类中完全实现,然后我将调用如下:

c.send_command("MUTLI");
c.send_command("SET", "foo", "bar");
c.send_command("GET", "foo");
c.send_command("EXEC");

当我检查调用了哪个方法实现时,我看到第三次调用(GET foo)最终到达了最后一个实现:

virtual void send_command( const std::string& command, bool pipeline = true );

其中“foo”被隐式转换为布尔值。当我使用显式 c-cast 对这样的字符串进行调用时,命中第二个实现(字符串、字符串、布尔值)的“SET”、“foo”、“bar”也同样重要

c.send_command("GET", (std::string)"foo");

预期的方法被调用。

我正在使用带有 C++11 的 gcc (GCC) 4.7.2 20121109 (Red Hat 4.7.2-8)。

4

3 回答 3

4

编译器更喜欢从const char*to的转换,而bool不是到 UDT ( std::string) 的转换。如果需要,也可以添加更多的重载const char*

于 2014-01-16T11:57:14.877 回答
4

您遇到了这样一个事实,即指针可以隐式转换为bool(测试它们不为空),并且字符串文字不是 a std::string,而是 aconst char[]衰减为const char*on call 。你可以做的是提供一个额外的重载const char*

void send_command(const std::string& command, const char* key)
{ send_command(command, std::string(key)); }

活生生的例子

于 2014-01-16T12:00:18.130 回答
1

重载解决有几个步骤:首先,选择一组可行的函数。考虑到省略号和/或默认参数,这些可行的函数必须具有足够的调用参数。此外,每个参数都必须可转换为相应的参数类型。因为c.send_command("GET", "foo");你有可行的候选人

virtual void send_command( const std::string&, const std::string&, bool);
virtual void send_command( const std::string&, bool);

因为前者的第三个参数是默认的,并且字符串字面量参数可以转换为string const&and bool

获得可行集后,编译器会查看所需的参数转换。不首选转换,然后是内置转换,然后是用户定义的转换。在这种情况下,第一个参数的转换在两个可行函数中是相同的。对于第二个参数,转换bool为 buitlin,而转换string const&为不是。因此send_command( const std::string&, bool);优于替代方案。

于 2014-01-16T12:08:55.463 回答