std::min/std::max作为模板比较器
std::min/std::max as template comparators
受本例使用std::less/std::greater
的启发。是否可以使用std::min
或std::max
作为模板比较器?
以下示例引发错误:
error: type/value mismatch at argument 1 in template parameter list for 'template<class C> class Test'
#include <functional>
#include <algorithm>
template <typename C>
class Test
{
public:
int compare(int x, int y)
{
return C()(x, y);
}
};
int main() {
Test<std::min<int>> foo;
Test<std::max<int>> bar;
foo.compare(1, 2);
bar.compare(1, 2);
}
注意std::min
和std::max
是函数模板。如果要将它们用作模板参数,则需要将它们声明为非类型模板参数,例如函数指针:
template <const int& (*C)(const int&, const int&)>
class Test
{
public:
int compare(int x, int y)
{
return C(x, y);
// ~~ Note no () here
}
};
std::min<int>
和std::max<int>
不是类型。它们是函数。
Test<std::min<int>>
Test
模板希望其参数是类(或者更确切地说是类型),而不是函数。模板声明为:
template <typename C> class Test
typename
表示模板参数是一个类/类型。
此外,该模板还声明了一个名为"compare"的方法。main()
尝试调用一个名为"run"的方法。那将是另一个问题。
它std::min和std::max是函数而不是类。可能使用Functor类模板包装std::min/max功能也是一个更好的选择,如下代码所示:
#include <iostream>
#include <functional>
#include <algorithm>
template <typename C>
class Test
{
public:
int compare(int x, int y)
{
return C()(x, y);
}
};
template<typename T>
class MinComp {
public:
T operator ()(T x, T y) {
return std::min<T>(x,y);
}
};
int main() {
Test<MinComp<int>> foo;
std::cout<<foo.compare(5, 2);
}
相关文章:
- std::设置自定义比较器
- C++中"std::sort"比较器的不同类型
- 将 std::set 与基于键的比较器一起使用
- std::为插入和排序设置不同的比较器
- std::用派生类对象设置,但用gcc8.1设置基类比较器
- 如何在 C++11 中将 std::max 与自定义比较器一起使用?
- 如何使用自定义比较器初始化类数据成员,该成员是 std::set
- std::<int>betterer() 比较器与 partial_copy_sort 的困难,在 Mac OSX 上"no matching function call.."
- 您可以将STD :: MAP变成带有自定义比较器的无序地图吗?
- STD ::与自定义比较器进行排序
- 如何为数据类型 vector<glm::vec3> (opengl 数据类型) 编写 std::minmax 函数的自定义比较器
- STD ::设置比较器,该比较器指的是外部值
- 用自定义比较器设置操作STD ::设置操作
- STD :: MAP,STD :: set and std :: Priority_queue中的比较器
- std::set 比较器功能如何工作?
- 为什么我不能重载我传递给 std::upper_bound 的比较器
- std::sort与不严格的弱排序比较器可以作为拓扑排序工作
- std::map 的比较器函数中的 SEG 故障/未定义行为
- std::list::使用自定义比较器排序时出现分段故障
- STD :: SET(或STD :: MAP)是否有一个提供基于值的查找的STL比较器?STD :: lands_les