动机为this example使用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
是函数模板。如果想将它们用作模板参数,则需要将它们声明为 non-type template parameter ,如函数指针:
template <const int& (*C)(const int&, const int&)>
class Test
{
public:
int compare(int x, int y)
{
return C(x, y);
// ~~ Note no () here
}
};
关于c++ - std::min/std::max 作为模板比较器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38602629/