即使看起来更合适,也不会考虑过载

问题描述 投票:3回答:2

gcc (live on godbolt)和clang都拒绝了它:

#include <string>

namespace
{
    std::string
    to_string(char const (&str) [14])
    { return str; }
}

void f()
{
    using std::to_string;
    char const hello[14] = "Hello, World!";
    (void) to_string(hello);
}

编译器考虑每个std::to_string overloads并得出以下结论:

std::to_string

如果删除error: no matching function for call to 'to_string(const char [14])' ,则会考虑并调用我的重载。为什么?如何解决(除了删除using以外)?

c++ overloading overload-resolution
2个回答
3
投票

使用声明的范围很重要。这是一个正确的声明,因此名称隐藏生效。在函数内部,全局作用域版本不可见。您需要重新引入它:

using std::to_string

2
投票

此使用声明

using ::to_string;
using std::to_string;

隐藏全局名称空间中的声明。因此,编译器看不到函数:: to_string。

所以你必须写

using std::to_string;

并使未命名的名称空间内联。

using std::to_string;
using ::to_string;
© www.soinside.com 2019 - 2024. All rights reserved.