我有一个关于我刚在工作中遇到的情况的问题。

设置:
在stringStuff.h中

namespace n1
{
namespace n2
{
    typedef std::string myString;
}
}

namespace n1
{
namespace n2
{
    void LTrim(myString& io_string);
    void RTrim(myString& io_string);

    inline void Trim(myString& io_string)
    {
        LTrim(io_string);
        RTrim(io_string);
    }
}
}

在impl.cpp中
#include "stringStuff.h" // This actually gets included via other include files
#include "globalInclude.h" // contains 'using namespace n1::n2;'. Yes, I know this isn't best practice

inline static myString Trim(const myString& in_string)
{
    // impl
}

static void impl(const myString& in_string, myString& out_string)
{
    size_t N = 10; // just some computed value.
    out_string = Trim(in_string.substr(1, N)); // This is the line with the error
}

现在,我承认我对C++名称解析规则的理解不尽如人意,但是当我看到这一点时,似乎对Trim的调用应该是模棱两可的。

令人惊讶的是,它可以使用GCC在Linux上正常编译,并调用impl.cpp中定义的函数。当我使用其 native 编译器在HP-UX上进行编译时,似乎可以将调用解析为stringStuff.h中定义的调用,并且提示将临时转换为非const引用(这是警告,而不是错误)。 ,以及有关尝试为myString分配void的信息。

根据C++标准应该发生什么情况,哪个编译器(如果有的话)正确处理?

顺便说一句,在我的案例中,我通过在调用trim之前加上::来“修复”了它,尽管那并不是很理想。

最佳答案

诀窍是一个采用const引用,另一个采用非const引用,因此它们是两个不同的函数,而不是同一个函数,其分辨率可能不明确。然后,它取决于调用中参数的类型。由于substr返回一个值,因此它只能绑定(bind)到const引用。因此,它应该在没有警告的情况下调用::Trim。我会说HP-UX编译器是错误的。

关于c++ - 澄清C++名称查找,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13300263/

10-12 14:51
查看更多