加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 编译器试图从int初始化enum类

发布时间:2020-12-16 10:04:33 所属栏目:百科 来源:网络整理
导读:我有一个enum类的类型,并希望输出类型名称的“to_string”函数,所以我在我自己的命名空间中编写.问题是,该命名空间中的其他函数试图调用to_string,例如,一个int(实际上只是一个int,不打算成为枚举的一部分)是找到自定义的to_string并给出关于枚举的无效初始
我有一个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)

A using-directive specifies that the names in the nominated namespace can be used in the scope in which the
using-directive appears after the using-directive. During unqualified name lookup (3.4.1),the names appear
as if they were declared in the nearest enclosing namespace which contains both the using-directive and the
nominated namespace
. [ Note: In this context,“contains” means “contains directly or indirectly”. — end
note ]

因此,出于查找的目的,名称空间b中的名称被视为它们在全局名称空间中.这意味着命名空间a中的f(char)将隐藏命名空间b中的f(int):

(C 14 3.3.10 / 4)

During the lookup of a name qualified by a namespace name,declarations that would otherwise be made
visible by a using-directive can be hidden by declarations with the same name in the namespace containing
the using-directive; see (3.4.3.2).

在您的示例中,在其他:: run()中调用to_string(42)将找到其他:: to_string,因为隐藏了std :: to_string(int).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读