是否可以回调模板类的成员?

问题描述 投票:0回答:2

如上所述,是否可以回调模板类的成员?我的意思是,我有一些模板类,有另一个(非模板)类的定义对象。该对象具有另一个成员函数。我想从该成员函数调用模板类的成员函数。这可行吗?

c++ templates callback
2个回答
3
投票

这就是我理解这个问题的方法。一个名为'some_class'(MyAlgorithm)的类应该具有对模板的引用(AlgorithmConsumer)。由于'some_class'只需要一个方法,最简单的方法是传递对函数的引用,如下所示:

#include <iostream>
#include <functional>


class MyAlgorithm
{
    std::function<void()> prepare;
public:
    explicit MyAlgorithm(std::function<void()> prepare)
        : prepare{prepare}
    {}

    void do_something()
    {
        if (prepare)
        {
            prepare();
        }

        std::cout << "I did something\n";
    }
};

template<typename T>
class AlgorithmConsumer
{
    MyAlgorithm algorithm;
public:
    AlgorithmConsumer()
        : algorithm([this](){prepare();})
    {}

    void prepare()
    {
        std::cout << "Preparing...\n";
    }

    void execute()
    {
        algorithm.do_something();
    }
};

int main()
{
    AlgorithmConsumer<int> ac;
    ac.execute();
    return 0;
}

希望,这解决了你的问题。


2
投票

这是一种不使用std::function的方法

struct B{ 


    template<class T>
    void CallTemplateFun(void (T::*funPtr)(), T& instance){

        (instance.*funPtr)();
    }


};

template<typename T>
class A{

    T t;
    B b;

public:

    A(T v) : t(v){}

    void print(){ std::cout << t << std::endl  ; }
};

int main(
{

    A<int> ai(5);
    B b;
    b.CallTemplateFun(&A<int>::print, ai);


    A<float> af(3.1428f);
    b.CallTemplateFun(&A<float>::print, af);


    return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.