簡體   English   中英

對於set iterator和const_iterator的輸入,不能重載成員函數(但可以用於其他stl迭代器)

[英]member function cannot be overloaded for input of set iterator and const_iterator (but can for other stl iterators)

編譯以下代碼

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中,成員是const。 這似乎得到了以下事實的證實:用vector替換set會使其完美地編譯。

奇怪的是,當我從結構中刪除函數並將它們放在全局命名空間中時

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(一個定義規則)(並且可能與鏈接器有重復的符號錯誤)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM