C++调用错误签名的函数

Sue*_*ode 2 c++

我有一个带有这个api的头文件:

class XmlTree {
    public:
    template<typename T> void Set(const std::string& path, const T& val, const std::string& attrib = "") {...}
    template<typename T> void Set(const std::string& path, const T& val, bool encrypt) {...}
}
Run Code Online (Sandbox Code Playgroud)

代码正在执行此行:

static XmlTree get_root_response(const string& api_name, int code = 0) {
    XmlTree output;
    //api_name is a const string&="Wut", code is an int=200
    output.Set<int>("/" + api_name, code, "code"); //on this line
    ...
    return output;
}
Run Code Online (Sandbox Code Playgroud)

由于某种原因,这会调用第二个Set函数签名而不是第一个.GDB显示了这个:

#1 XmlTree::Set<int> (this=address, path="/Wut", val=@address: 200, encrypt=true)
#2 get_root_response(api_name="Wut", code=200)
Run Code Online (Sandbox Code Playgroud)

很明显,正在调用错误的函数签名,但我不知道它究竟是如何得到错误的bool输入.任何人都知道为什么会发生这种情况?

Som*_*ken 6

这是因为它"code"const char[]衰变的类型const char*.

指针类型可以隐式转换为bool(计算到true此处),同时std::string需要构造函数调用来构造第std::string一个.所以bool过载是有利的,因此被选中.

您可以先通过创建临时字符串来解决此问题:

output.Set<int>("/" + api_name, code, std::string("code"));
Run Code Online (Sandbox Code Playgroud)