首页 > 解决方案 > 如何将谓词函数作为模板参数传递?

问题描述

我有一个简单的谓词:

class less_than
{
  int  x;

public:
  less_than(int i):
    x(i)
  {
  }

  bool  operator()(int i) const
  {
    return i < x;
  }
};

我有一个看起来像这样的容器:

my_containers<std::list<int>, less_than, int> myCont(list_1, list_2, less_than(11));

我试图像这样创建我的模板:

template<class Type, class Predicate, class Item_Stored>
class my_containers
{
public:
  my_containers(Type &tar_1, Type &tar_2, Predicate felt)
  {
    ItemList_1 = tar_1;
    ItemList_2 = tar_2;
    predIcate  = felt;
  }

  my_containers & insert(const Item_Stored put_in)
  {
    if (!predIcate.operator()(put_in))
    {
      ItemList_1.insert(ItemList_1.end(), put_in);
    }
    else
    {
      ItemList_2.insert(ItemList_2.end(), put_in);
    }

    return *this;
  }

private:
  Type       ItemList_1;
  Type       ItemList_2;
  Predicate  predIcate;
};

每次我使用时,如果它小于给定的值.insert(x),它应该添加到第一个列表中,否则添加到另一个列表中,但它给了我这个错误:xless_than::x

Error   C2512   'less_than': no appropriate default constructor available   

我该如何解决?

标签: c++templatespredicatefunctorc++98

解决方案


您的构造函数需要每个成员的默认构造函数。改用成员初始化器列表

    my_containers(Type& tar_1, Type& tar_2, Predicate felt)
        :ItemList_1(tar_1), ItemList_2(tar_2), predIcate(felt){}

参考:https ://en.cppreference.com/w/cpp/language/constructor 。


推荐阅读