LINUX.ORG.RU

[C++] имя метода как аргумент — как?

 


0

0

нужно передать внутри одного класса методу имя другого метода как
параметр. пробую так:

#include <stdio.h>

class abc {
public:
    int sum(int x, int y) { return x + y; }

    int act(int (*f)(int, int), int x, int y) { return f(x, y); }

    int res(int a, int x, int y) {
        if(a == 1) {
            return act(sum, x, y);
        }
        return 0;
    }
};

int
main(int argc, char **argv) {
    abc a;

    printf("%d\n", a.res(1, 5, 6));

    return 0;
}



$ g++ -Wall -c -o test.o test.cpp
test.cpp: In member function `int abc::res(int, int, int)':
test.cpp:11: error: no matching function for call to `abc::act(<unknown type>, int&, int&)'
test.cpp:7: note: candidates are: int abc::act(int (*)(int, int), int, int)
make: *** [test.o] Error 1


с обычными функциями (без классов) все работает номально
anonymous

попробуй так (нет компилятора под рукой, чтобы проверить):

class abc {
public:
    int sum(int x, int y) { return x + y; }

    int act(int (*f)(void *, int, int), int x, int y) { return f(this, x, y); }

    int res(int a, int x, int y) {
        if(a == 1) {
            return act(sum, x, y);
        }
        return 0;
    }
};

uj2 ★★★
()
Ответ на: комментарий от uj2

не, так тоже не работает:

test.cpp: In member function `int abc::res(int, int, int)':
test.cpp:11: error: no matching function for call to `abc::act(<unknown type>, int&, int&)'
test.cpp:7: note: candidates are: int abc::act(int (*)(void*, int, int), int, int)
make: *** [test.o] Error 1


не очень понимаю почему должно было -- прототип функции  int(*f)(void*, int, int) не совпадает с методом sum(int, int)

попробовал также sum(void*, int x, int y) -- обратно не работает


вот почему-то компилер упорно пишет no matching function for call to
abc::act(<unknown type>, int&, int&) -- почему int& а нет просто int?

anonymous
()

#include <stdio.h>

class abc {
public:
    int sum(int x, int y) { return x + y; }

    int act(int (abc::*f)(int, int), int x, int y) { return (this->*f)(x, y); }

    int res(int a, int x, int y) {
        if(a == 1) {
            return act(&abc::sum, x, y);
        }
        return 0;
    }
};

int
main(int argc, char **argv) {
    abc a;

    printf("%d\n", a.res(1, 5, 6));

    return 0;
}

vasirck
()
Ответ на: комментарий от vasirck

О! отлично, работает

спасибо

anonymous
()

> нужно передать внутри одного класса методу имя другого метода
> какпараметр. пробую так:
>
> #include <stdio.h>
>
> class abc {
> public:
> int sum(int x, int y) { return x + y; }

В данном случае проще всего объявить передаваемый метод как static.
Если это не проходит, то через member pointer, как описано выше.

int19h ★★★★
()
Ответ на: комментарий от int19h

это не совсем подходит. тем не менее спасибо за ликбез, буду иметь в виду

anonymous
()

Обобщенное решение:


#include <iostream>
#include <boost/bind.hpp>

class abc {
public:
    int sum(int x, int y) { return x + y; }

    template <class functorT>
    int act(functorT f, int x, int y) { return f(x, y); }

    int res(int a, int x, int y) {
      if (a == 1) 
	{
	   return act(boost::bind(&abc::sum, this, _1, _2), x, y);
        }
        return 0;
    }
};

int main() 
{
    abc a;
    std::cout << a.res(1, 5, 6) << std::endl;
}

aton
()
Вы не можете добавлять комментарии в эту тему. Тема перемещена в архив.