当前位置:网站首页>How do std:: function and function pointer assign values to each other

How do std:: function and function pointer assign values to each other

2022-07-04 11:20:00 Ascetic monk runnercai

Let's look at the official code first :

#include <functional>
#include <iostream>
 
int f(int, int) {
     return 1; }
int g(int, int) {
     return 2; }
void test(std::function<int(int, int)> const& arg)
{
    
    std::cout << "test function: ";
    if (arg.target<std::plus<int>>())
        std::cout << "it is plus\n";
    if (arg.target<std::minus<int>>())
        std::cout << "it is minus\n";
 
    int (*const* ptr)(int, int) = arg.target<int(*)(int, int)>();
    if (ptr && *ptr == f)
        std::cout << "it is the function f\n";
    if (ptr && *ptr == g)
        std::cout << "it is the function g\n";
}
 
int main()
{
    
    test(std::function<int(int, int)>(std::plus<int>()));
    test(std::function<int(int, int)>(std::minus<int>()));
    test(std::function<int(int, int)>(f));
    test(std::function<int(int, int)>(g));
}

After reading it, I found it was very simple , But in practice, you find that you tartget After that, why nullptr
This is because you used bind, It was used bind Then the type changed .
tartget pit

原网站

版权声明
本文为[Ascetic monk runnercai]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202141408353304.html