search

Home  >  Q&A  >  body text

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)可以编译通过。

高洛峰高洛峰2774 days ago454

reply all(3)I'll reply

  • 大家讲道理

    大家讲道理2017-04-17 13:40:17

    Your type is wrong bool(*)(int,int)

    std::cout << zz::max<int, bool(*)(int,int)>(1, 2, ptr);
    

    reply
    0
  • PHP中文网

    PHP中文网2017-04-17 13:40:17

    You forcibly assigned comp as a bool instead of a function

    reply
    0
  • ringa_lee

    ringa_lee2017-04-17 13:40:17

    You don’t need to specify the type, C++ can automatically infer it. .
    zz::max(1, 2, ptr)

    reply
    0
  • Cancelreply