【问题标题】:How to use custom class pointer comparator inside class being compared如何在被比较的类中使用自定义类指针比较器
【发布时间】:2020-03-17 01:40:28
【问题描述】:

我正在尝试使用自定义比较器,如下面的最小示例:

#include <set>
using namespace std;

struct idComp;

class TestClass
{
   public:
      int id;
      void setId(int i){ id = i; }
      int getId(){ return id; }
      void test( set<TestClass*, idComp> &s){
         //do my stuff 
      }
      void test2(){
         set <TestClass*, idComp> s;
      }
};

struct idComp
{
   bool operator() (TestClass* t1, TestClass* t2) const
   {
      return t1->getId() < t2->getId();
   }
};

int main(int argc, char* argv[])
{
   return 0;
}

...但是当我尝试编译时,出现以下与 test 函数相关的错误:

comp_ref.cpp:12:34: error: ‘idComp’ was not declared in this scope
       void test( set<TestClass*, idComp> &s){
                                  ^~~~~~
comp_ref.cpp:12:40: error: template argument 2 is invalid
       void test( set<TestClass*, idComp> &s){

加上test2:

/usr/include/c++/7/bits/stl_tree.h:708:31: error: invalid use of incomplete type ‘struct idComp’
       _Rb_tree_impl<_Compare> _M_impl;

关于如何/在哪里定义 idComp 以便函数 test 可以使用的任何建议?

【问题讨论】:

  • 您的 C++ 编译器是逻辑实体。它从头到尾读取您的程序,而不是从头到尾。因此,当您的编译器读取您的程序并对其进行编译并到达void test( set&lt;TestClass*, idComp&gt; &amp;s) 部分时,您如何期望您的编译器在这一点上知道idComp 的任何信息,甚至知道它是什么?

标签: c++ class comparator


【解决方案1】:

由于您有一点循环依赖,您可以通过在 TestClass 之前前向声明 idComp 来解决此问题:

struct idComp;

class TestClass
{
   ...

但您可以将struct idComp 的定义留在原处。

【讨论】:

  • 不错。对 test2 的第二个错误有什么想法吗? (编辑/添加到代码示例)
  • @skellpco 不确定。最好为此创建另一个问题。
猜你喜欢
  • 2017-02-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多