c – 编译器试图从int初始化enum类
我有一个enum类的类型,并希望输出类型名称的“to_string”函数,所以我在我自己的命名空间中编写.问题是,该命名空间中的其他函数试图调用to_string,例如,一个int(实际上只是一个int,不打算成为枚举的一部分)是找到自定义的to_string并给出关于枚举的无效初始化的错误.
我知道我可以显式调用std :: to_string而不是to_string,但我认为有更好的方法.我究竟做错了什么? Here是示例代码: #include <iostream> #include <string> namespace other { enum class Type { Type1,Type2 }; std::string to_string(const Type& type) { switch(type) { case Type::Type1: return "Type1"; break; case Type::Type2: return "Type2"; break; default: {} } return "Unknown"; } void run() { using namespace std; cout << string("Type: ") + to_string(Type::Type1) << endl; cout << string("int: " ) + to_string(42) << endl; // this one generates compile-time errors } } int main() { other::run(); using namespace std; cout << string("int: " ) + to_string(42) << endl; // This one is ok return 0; } 解决方法
这是一个棘手的情况,涉及名称空间的一些细微规则.让我们考虑一个更简单的例子:
namespace b { void f(int) { } } namespace a { using namespace b; void f(char) { } void g() { f(5); // calls f(char) } } 这里的问题是,即使我们使用了命名空间b,b中的声明也被视为为了查找而在公共命名空间(全局)中声明它们: (C 14 7.3.4 / 2)
因此,出于查找的目的,名称空间b中的名称被视为它们在全局名称空间中.这意味着命名空间a中的f(char)将隐藏命名空间b中的f(int): (C 14 3.3.10 / 4)
在您的示例中,在其他:: run()中调用to_string(42)将找到其他:: to_string,因为隐藏了std :: to_string(int). (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |