编译以下代码
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/