C++ std::min/std::max作为模板比较器
通过使用C++ std::min/std::max作为模板比较器,c++,templates,c++14,C++,Templates,C++14,通过使用std::less/std::greater激发。 是否可以使用std::min或std::max作为模板比较器 以下示例引发错误: 错误:“模板类测试”的模板参数列表中参数1的类型/值不匹配。 #include <functional> #include <algorithm> template <typename C> class Test { public: int compare(int x, int y) {
std::less/std::greater
激发。
是否可以使用std::min
或std::max
作为模板比较器
以下示例引发错误:
错误:“模板类测试”的模板参数列表中参数1的类型/值不匹配。
#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);
}
#包括
#包括
模板
课堂测试
{
公众:
整数比较(整数x,整数y)
{
返回C()(x,y);
}
};
int main(){
测试食品;
试棒;
foo.比较(1,2);
比较(1,2);
}
std::min
和std::max
不是类型。它们是函数
Test<std::min<int>>
typename
表示模板参数是类/类型
此外,模板声明了一个名为“compare”的方法main()
尝试调用名为“run”的方法。这将是另一个问题。It 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);
}
#包括
#包括
#包括
模板
课堂测试
{
公众:
整数比较(整数x,整数y)
{
返回C()(x,y);
}
};
模板
MinComp类{
公众:
T运算符()(tx,ty){
返回标准::最小值(x,y);
}
};
int main(){
测试食品;
std::cout注意和是函数模板。如果要将它们用作模板参数,需要将它们声明为,例如函数指针:
template <const int& (*C)(const int&, const int&)>
class Test
{
public:
int compare(int x, int y)
{
return C(x, y);
// ~~ Note no () here
}
};
模板
课堂测试
{
公众:
整数比较(整数x,整数y)
{
返回C(x,y);
//~~注意这里没有()
}
};
谢谢我修复了函数名,std::less
为什么会起作用而不std::min
?@pyCthonstd::less
是一个struct
,std::min
是一个函数,有两个模板参数,template?
@pyCthon是的,你可以。把它们用作Test foo;
。
template <const int& (*C)(const int&, const int&)>
class Test
{
public:
int compare(int x, int y)
{
return C(x, y);
// ~~ Note no () here
}
};