所以我想使用对象仿函数对子类中母类中的数组进行排序。母类是通用的。
template<typename T>
class MotherClass
{
public:
/* some code */
std::list<T*> getList();
private:
std::list<T*> list_;
}
子类使用另一个类作为模板
class OtherClass
{
public:
/* some code */
std::string getName() const;
private:
std::string name_;
}
这是仿函数类
class Functor
{
public:
/* some code */
bool operator() (OtherClass* a, OtherClass* b) const
{
return a->getName() < b->getName();
}
}
最后是子类
class ChildClass : public MotherClass<OtherClass>
{
public:
/* some code */
friend std::ostream& operator<<(std::ostream& o, const ChildClass& child);
}
std::ostream& operator<<(std::ostream& o, const ChildClass& child)
{
Functor functor;
std::sort(child.getList().begin(), child.getList().end(), functor);
/* some code */
}
当我评论 ChildClass 中的排序行时,解决方案构建没有任何问题。但是,当它存在时,会发生此错误。
error C2784: 'unknown-type std::operator -(std::move_iterator<_RanIt> &,const std::move_iterator<_RanIt2> &)': could not deduce template argument for 'std::move_iterator<_RanIt> &' from 'std::_List_unchecked_iterator>>'
有人可以帮忙吗?
最佳答案
如 std::sort
所述 documentation它需要随机访问迭代器,std::list
没有提供。这就是为什么 std::list
有自己的方法 std::list::sort
所以解决方案可能是:
Functor functor;
auto list = child.getList();
list.sort( functor );
注意:即使您使用支持随机访问迭代器的容器,您的方法也不会起作用,每次调用 child.getList()
都会创建一个新拷贝,所以您会得到 UB在 2 个不同的实例上调用 begin()
和 end()
。如果您的想法是对数据成员进行排序,则需要通过引用返回它,这不是一个好主意,但在技术上可行:
// if getList() returns reference this would work
Functor functor;
child.getList().sort( functor );
但最好将仿函数传递给 MotherClass
的方法,这样会对其进行排序
数据。
关于c++ - 在 c++ 中使用自定义仿函数对数组进行排序,其中母类是通用的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40725885/