首页 > c++模板函数问题

c++模板函数问题

#include <iostream>

namespace zz
{
    template <typename T>
    inline const T& min(const T& a, const T& b)
    {
        return b < a ? b : a;
    }

    template <typename T>
    inline const T& max(const T& a, const T& b)
    {
        return a < b ? b : a;
    }

    template <typename T, typename Compare>
    inline const T& max(const T& a, const T& b, Compare comp)
    {
        return comp(a, b) ? b : a;
    }
}

bool com(int a, int b)
{
    return a > b;
}

int main()
{
    bool (*ptr)(int, int);
    ptr = com;
    
    std::cout << zz::max<int, bool>(1, 2, ptr);
    return 0;
}



错误信息:

D:\c++code\c++stl\t16.cpp: In instantiation of 'const T& zz::max(const T&, const T&, Compare) [with T = int; Compare = bool]':
D:\c++code\c++stl\t16.cpp:34:43:   required from here
D:\c++code\c++stl\t16.cpp:20:14: error: 'comp' cannot be used as a function
   return comp(a, b) ? b : a;

请问报这个错是怎么回事啊?如果我把函数调用修改为zz::max(1,2,ptr)可以编译通过。


你强行把comp指派为一个bool而不是函数呀


你不用特意指定类型,c++也可以自动推断出来的。。
zz::max(1, 2, ptr)


你的类型啊写的不对啊 bool(*)(int,int)

std::cout << zz::max<int, bool(*)(int,int)>(1, 2, ptr);
【热门文章】
【热门文章】