重载函数作为参数进行回调。

通常调用一个重载函数会自动匹配,寻找最优函数。

但是如果作为回调函数,那么通常会出错,但是我们确实又有这个需求。

所以,可以通过一个指针来进行显示声明某个版本。

#include<iostream>
#include <typeinfo>
#include<string>
template <typename T1,typename T2>
void show(T1&& a,T2&&b)
{
    a(b);
    std::cout<<&b<<":b:"<<b<<std::endl;
}

void cor(int &c)
{
    c = 15;
    std::cout<<&c<<std::endl;
}

void cor(std::string c)
{
    std::cout<<&c<<std::endl;
}


int main()
{
    int a=1,b=2;
    std::cout<<&b<<":b:"<<b<<std::endl;
    void (*callback)(int&) = cor;
    show(callback,2);
    std::cout<<&a<<":a:"<<a<<std::endl;
    // show(a,b);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/rubikchen/article/details/89848557