如何将std ::函数分配给C 的操作员
How do I assign an std::function to an operator in C++?
template<class Key, class Value>
AVLTree<Key,Value>::AVLTree(){
this->lessThan = Key::operator<;
}
此代码应该使std::function<bool(Key, Key)> lessThan
字段等于密钥&lt;默认情况下运算符。但是,当我使用AVLTree<int,int>
尝试一下时,我会得到:
error: ‘operator<’ is not a member of ‘int’
我是错了这个错误的,还是在C ?
在C 中没有预先存在的函数可以在int
s上进行比较。此外,即使Key
是类类型,您也不知道它是成员还是非会员operator<
。
这里有一些替代方法:
使用
std::less
,this->lessThan = std::less<Key>();
使用lambda:
this->lessThan = [](const Key& k1, const Key& k2){ return k1 < k2; };
如果设计
<</p> <</p> <</p> <</p>AVLTree
喜欢标准库容器,则比较对象的类型应为类型模板参数Comp
默认为std::less<Key>
,并在构造函数中传递了一个实例,默认为Comp()
。
template<class Key, class Value>
AVLTree<Key,Value>::AVLTree()
{
this->lessThan = std::less<Key>();
}
http://en.cppreference.com/w/cpp/utility/functional/less
您需要针对int
,double
,char
等内置类型实现模板专业化。失败。
相关文章:
- 为什么我不能拥有纯虚拟分配操作员?
- 从私人矢量中公开访问和分配操作员
- 当直接分配时,为什么此功能指针分配起作用,而不是与有条件的操作员一起使用
- 如何使用变速操作员<<分配BH1750光传感器中的值?
- C 分配操作员助手
- C BigInteger和分配操作员超载
- C 新操作员分配新内存
- 复制构造函数和复制分配操作员
- 我可以分配成员访问操作员的返回值吗?
- 对模板中的过载分配(=)操作员
- 复制构造函数和分配操作员对循环依赖类别的过载
- 新操作员如何知道需要为特定类分配多少尺寸
- 用两个参数调用新操作员,但没有分配
- 分开副本/移动分配操作员
- 如何超载分配运算符,该操作员总计两个实例变量
- 复制分配操作员定义
- 不清楚的副本分配操作员示例
- C 复制分配操作员问题
- 虚拟分配操作员不允许static_cast
- 在班级中使用动态分配的C风格字符串,并带有复制和分配操作员,给出了意外的结果