c++ - std::min/std::max 作为模板比较器

标签 c++ templates c++14

动机为this example使用std::less/std::greater 。 是否可以使用std::minstd::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::minstd::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/

相关文章:

c++ - stringstream 的第一个字符串参数被保存为指针/垃圾

c++ - g++ 中的递归 lock() 调用

c++ - 没有 Boost 的现代 C++ 中的 bimap 实现

C++ 智能指针范围和资源删除

c++ - "#include&lt"和#include之间的区别”

c++ - Boost 系统 1.69.0 不只是标题?

c++ - 为什么只有样本计数不同时 avcodec_fill_audio_frame 返回 -22?

c++ - 平方根元函数?

c++ - 确定枚举类中枚举的数量(或任何枚举类中的特定枚举值)

c++ - 模板规范的不存在属性