在类中调用模板
Calling template in class
本文关键字:调用 更新时间:2023-10-16
我希望创建一个多个类可以使用的静态布尔模板函数。我使用此函数作为比较器对点向量进行排序。这是我到目前为止所做的:
类.h
class Point2D
{
protected:
int x;
int y;
public:
int getX();
int getY();
Point2D();
Point2D(int x, int y);
template< typename T>
T sortAscending(T a, T b )
{
return a.getX() < b.getX();
}
static bool sortAscending(Point2D a, Point2D b);
}
主内.cpp
// my vector contains objects of Point2D that i wish to
//sort according to the value of x coordinates.
sort(p2Vec.begin(),p2Vec.end(),Point2D::sortAscending);
给我错误:
错误:调用没有匹配函数 'sort(std::vector::iterator, std::vector::iterator, ('
有谁知道我做错了什么?
在这里使用 lambda 函数,如下所示:
std::sort(p2Vec.begin(),p2Vec.end(),
[](const Point2D & p1, const Point2D & p2) {
return Point2D::sortAscending( p1, p2);
});
看这里
语法为:
std::sort(p2Vec.begin(), p2Vec.end(), &Point2D::sortAscending<Point2D>);
并要求该方法static
。
但最好在外面创建一个结构:
struct LessByGetX
{
template <typename T>
bool operator () (const T& lhs, const T& rhs) const
{
return lhs.getX() < rhs.getX();
}
};
并使用它:
std::sort(p2Vec.begin(), p2Vec.end(), LessByGetX{});
或者,您可以直接使用 lambda:
std::sort(p2Vec.begin(), p2Vec.end(), [](const T& lhs, const T& rhs)
{
return lhs.getX() < rhs.getX();
});
相关文章:
- 什么时候调用组成单元对象的析构函数
- 对RValue对象调用的LValue ref限定成员函数
- 为什么使用 "this" 指针调用派生成员函数?
- 函数调用中参数的顺序重要吗
- OpenGL - 在抛出"__gnu_cxx::recursive_init_error"实例后终止调用?
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 为什么我的C#代码在调用回C++COM直到Task时会暂停.等待/线程.加入
- 在c++类上调用void函数
- 为什么 std::unique 不调用 std::sort?
- 调用专用模板时出错"no matching function for call to [...]"
- 选择要调用的构造函数
- C++为什么尽管我调用了void函数,它却不起作用
- 构造函数正在调用一个使用当前类类型的函数
- 变量没有改变?通过向量的函数调用
- 没有为自己的结构调用列表推回方法
- 调用'begin(int [n])'没有匹配函数
- 什么时候调用析构函数
- 如何用参数值调用函数(仅在运行时已知)
- std::cout.imbue()多重调用
- 函数何时会在c++中包含stack_Unwind_Resume调用