c++模板函数问题

查看:100
本文介绍了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)可以编译通过。

解决方案

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

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

这篇关于c++模板函数问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆