c++ - 成员函数不能为 set iterator 和 const_iterator 的输入重载(但可以为其他 STL 迭代器重载)

标签 c++ stl iterator language-lawyer overloading

编译以下代码

struct foo {
    int foo(std::set<int>::iterator);
    int foo(std::set<int>::const_iterator);
};

我从 gcc (mingw) 得到以下错误

func.cpp:5:9: error: 'int functor::foo(std::set<int>::const_iterator)' cannot be overloaded
    int foo(std::set<int>::const_iterator);

func.cpp:4:9: error: with 'int functor::foo(std::set<int>::iterator)'
    int foo(std::set<int>::iterator);

我从 msvc 和 clang 得到了类似的错误。我猜想问题是它们代表相同的底层类型 因为在 std::set 中,成员是常量。将 set 替换为 vector 导致它的事实似乎证实了这一点 comile 非常好。

奇怪的是,当我从结构中删除函数并将它们放入全局命名空间时

int foo(std::set<int>::iterator);
int foo(std::set<int>::const_iterator);

它编译没有错误。这可能是由于我不知道的非成员函数的不同重载规则,我不确定

所以我的问题:

  • 为什么不允许这种重载?
  • 为什么将它们放在全局命名空间中允许它们编译?

最佳答案

在全局范围内,这些只是同一个函数的声明(当两个迭代器是相同类型时)。

int foo(std::set<int>::iterator);
int foo(std::set<int>::const_iterator);

在类中,不能对同一个方法声明两次。

如果您定义函数:

int foo(std::set<int>::iterator) {return 0;}
int foo(std::set<int>::const_iterator) {return 0;} // program is ill formed (when iterator are same type)

您使用同一函数的 2 个定义打破了 ODR(一个定义规则)(并且可能有链接器的重复符号错误)。

关于c++ - 成员函数不能为 set iterator 和 const_iterator 的输入重载(但可以为其他 STL 迭代器重载),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52085240/

相关文章:

c++ - "pure virtual function called"在 gcc 4.4 上,但不在新版本或 clang 3.4 上

c++ - 共享指针的排序列表

c# - 如何将 vector<int> 从 C++ dll 编码到 C# 应用程序?

不同编译器中的 C++ 标准库实现

c++ - 读写迭代器 - C++

c++ - 我可以将反向迭代器转换为正向迭代器吗?

c++ - 混淆 L 值和 R 值括号

c++ - OOP 游戏菜单系统开发概念化

c++ - 为什么 Scott Meyers 建议更喜欢 `iterator` 而不是 `const_iterator`

java - 在 Java 中显示列表与在 Python 中一样优雅