Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ssis/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ C++;:如何允许自己的比较运算符()?_C++_Stl - Fatal编程技术网

C++ C++;:如何允许自己的比较运算符()?

C++ C++;:如何允许自己的比较运算符()?,c++,stl,C++,Stl,我有一个自定义列表类,希望使用STL中已知的“比较运算符”支持操作。例如: std::list<MyClass> d; struct not_key { not_key( std::string const& str) : str_(str) {} bool operator( MyClass& elem ) { return !elem.findThatThing(); } std::string str_; };

我有一个自定义列表类,希望使用STL中已知的“比较运算符”支持操作。例如:

std::list<MyClass> d;
struct not_key {
    not_key( std::string const& str) : str_(str) {}

    bool operator( MyClass& elem ) {
        return !elem.findThatThing();
    }

    std::string str_;
};


not_key comp("value");
d.remove_if( comp );

mylist<MyClass> e(d);
e.filter( comp );
std::列表d;
结构非U键{
not_键(std::string const&str):str_键(str){}
布尔运算符(MyClass&elem){
return!elem.findThatThing();
}
std::string str;
};
非关键公司(“价值”);
d、 如有必要,移除_(组件);
mylist e(d);
e、 滤波器(comp);
我正在努力寻找一个接受这些“一般”比较运算符的方法的签名。因为它们都有不同的类型,我不想要静态成员函数。如何向类中添加接受比较运算符的方法


非常感谢!:)

签名应为:

bool operator()(Myclass const & elem) const
标准函数(如
std::sort
)使用一个模板参数,该参数被推断为比较函数的类型,如对象:

template <class UnaryPredicate>
void filter(UnaryPredicate func) {
  // Call it like:
  func(something);
}

如果您的意思是想知道mylist::filter的签名,您可能只需要将其设置为具有Pred或与类型类似的模板

template< typename T >
class mylist
{
   public:
      template< typename Pred >
      void filter( Pred pred )
      {
          // implement, calling pred(elem) for each element or pred(*iter)
      }
};
模板
类mylist
{
公众:
模板
空隙过滤器(Pred Pred)
{
//实现,为每个元素或pred(*iter)调用pred(elem)
}
};
请注意,您可以将一个自由函数传递到该模板函数中,在C++11中,您可以传递一个lambda


如果您想要的不是模板(元素类型除外),可以使用
boost::function
(或
std::function

可能是真的,但不是答案。。。。如果您希望函数定义位于类之外(尽管它仍应位于头文件中),则需要
模板内联void mylist::filter(Pred Pred){/*…*/}
template< typename T >
class mylist
{
   public:
      template< typename Pred >
      void filter( Pred pred )
      {
          // implement, calling pred(elem) for each element or pred(*iter)
      }
};