c++ - 如何将谓词函数作为模板参数传递?
问题描述
我有一个简单的谓词:
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));
- 第一个参数说明
list_1
and的类型是什么list_2
。 - 第二个参数表示谓词的名称。
- 第三个参数表示
list_1
and的项目类型是什么list_2
。
我试图像这样创建我的模板:
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)
,它应该添加到第一个列表中,否则添加到另一个列表中,但它给了我这个错误:x
less_than::x
Error C2512 'less_than': no appropriate default constructor available
我该如何解决?
解决方案
您的构造函数需要每个成员的默认构造函数。改用成员初始化器列表。
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 。
推荐阅读
- c# - 从 xml 检索数据的问题
- php - Php电子邮件表单不从网络电子邮件表单发送电子邮件
- javascript - SyntaxError: Unexpected token { 同时从文件导入函数
- python - 如何知道操纵杆是否是pygame中的XInput?
- javascript - 如何使用 immutable.js 在 reducer 中编写给定状态?
- sql - 如何根据同一张表上的不同标准对相同的数据进行分组和求和
- javascript - 为什么我输入函数,循环不能正常工作,但在全球范围内它确实有效
- shell - GNUPLOT : 一种将数据传输到 gnuplot 脚本的更好方法
- javascript - 调用 createAnswer 不会改变 `signallingState`
- laravel - 在 laravel 中向添加的用户显示项目