Пример передачи указателя на функцию-член в глобальную переменную из другой функции-члена - PullRequest
0 голосов
/ 09 марта 2020

Есть много примеров использования std :: function для передачи указателя на функцию-член. Я построил простой и компактный пример конкретного приложения c, которое часто появляется в научном программировании c. Например, может потребоваться интегрировать различные функции-члены класса в другую функцию-член. Процедура интеграции может быть глобальной или локальной функцией (в моем примере это глобальная функция). Я публикую этот пример, чтобы поделиться с другими не очень продвинутыми программистами. Моя вторая цель - предложить комментарии относительно эффективности, надежности этого подхода и альтернатив, таких как использование функций stati c. Буду признателен за любые отзывы.

myclass.h

#pragma once
#include <iostream>
#include <functional>
using namespace std::placeholders;
class myclass

class myclass
{

public:

int calledfunction1(int a, int b);
int calledfunction2(int a, int b);

int callingfunction(int& a, int& b, int& c);

};    

myclass. cpp:

#include "myclass.h"
int myfunction(std::function<int(int, int)> fun, int& a, int& b)
{
    return fun(a, b);
}
int myclass::calledfunction1(int a, int b)
{
     printf(" calledfunction: %d + %d = %d", a, b, a + b);
     std::cout << std::endl;

     std::cout << " calledfunction: a = " << a << std::endl;

     return 2*a;
}
    int myclass::calledfunction2(int a, int b)
{
     printf(" calledfunction: %d + %d = %d", a, b, a + b);
     std::cout << std::endl;

     std::cout << " calledfunction: a = " << a << std::endl;

     return 3*a;
}
int myclass::callingfunction(int& a, int& b, int& c)
{
    auto fp1 = std::bind(&myclass::calledfunction1, this, _1, _2);
    auto fp2 = std::bind(&myclass::calledfunction2, this, _1, _2);

    if (c == 1)
     {
         std::cout << " callingfunction #1" << std::endl;
         x = myfunction(fp1, a, b);
    }

    if (c == 2)
    {
        std::cout << " callingfunction #2" << std::endl;
        x = myfunction(fp2, a, b);
    }

    std::cout << " callingfunction#after" << std::endl;

    return x;
}

main. cpp

// example taken from 
// https://stackoverflow.com/questions/12662891/how-can-i-pass-a-member-function-where-a-free-function-is-expected

#include <iostream>
#include "myclass.h"

int main()
{
    std::cout << "Hello World!\n";

    myclass obj;

    int a = 2;
    int b = 3;

    int c = 1;
    int x = obj.callingfunction(a, b, c);
    std::cout << " main: c = " << c << " and  x = " << x <<std::endl;
    c = 2;
    x = obj.callingfunction(a, b, c);
    std::cout << " main: c = " << c << " and  x = " << x << std::endl;
    std::cout << std::endl;
}
...