c++ - 指向模板类方法的函数指针

标签 c++ c++14

我正在尝试实现以下代码模式。

struct Worker {
    void update(/* function pointer */) {

        for(unsigned int i = 0; i < 10; i++) {
            /* function execution */
        }
    }
}

template <typename t_derive>
struct BaseCrtp {
    void method1() {
        static_cast<t_derive*>(this)->method1();
    }

    void method2() {
        static_cast<t_derive*>(this)->worker.update(/*fptr of Derived1::method2*/);
    }
}

struct Derived1 : public BaseCrtp<Derived1> {
    Worker worker;

    void method1() {
        std::cout << "Derived1::method1" << std::endl;
    }

    void method2() {
        std::cout << "Derived1::method2" << std::endl;
    }
}

我想在 Worker::update 的实例中调用 Derived1 的方法 2。如何定义可以注入(inject)更新函数的函数指针。

最佳答案

struct Worker {
    void update(/* function pointer */) {
     .....

制作Worker::update一个模板成员函数:

struct Worker {
    template<typename Func>
    void update(Func&& func) {
     .....

或使用 std::function :

struct Worker {
    void update(std::function<void()> func) {
     .....

然后在您的 BaseCrtp<>::method2 中通过 lambda 传递回调如下:

void method2() {
    static_cast<t_derive*>(this)->worker.update(
        [this]{ static_cast<t_derive*>(this)->method2(); }
    );
}

完整示例:

#include <iostream>
#include <functional>

struct Worker {

    template<typename Func>
    void update(Func&& func) {
        for(unsigned int i = 0; i < 10; i++) {
            func();
        }
    }

    //alternatively....
    //
    //void update(std::function<void()> func) {
    //    for(unsigned int i = 0; i < 10; i++) {
    //        func();
    //    }
    //}
};

template <typename t_derive>
struct BaseCrtp {
    void method1() {
        static_cast<t_derive*>(this)->method1();
    }

    void method2() {
        static_cast<t_derive*>(this)->worker.update(
            [this]{ static_cast<t_derive*>(this)->method2(); }
        );
    }
};

struct Derived1 : public BaseCrtp<Derived1> {
    Worker worker;

    void method1() {
        std::cout << "Derived1::method1" << std::endl;
    }

    void method2() {
        std::cout << "Derived1::method2" << std::endl;
    }
};

template<typename T>
void process(BaseCrtp<T>& t){
    t.method2();
}

int main(){
    Derived1 d1;
    process(d1);
}

如图所示herehere ( std::function alternative) .


关于c++ - 指向模板类方法的函数指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41692652/

相关文章:

c++ - C++中的回文数

c++ - 使用 std::tuple_size 时产生 `error: incomplete type`

C++:我的右值在哪里?

c++ - Direct3D11 只渲染线条,而且顺序很奇怪

c++ - ImpersonateLoggedOnUser 无法在 Windows 服务中工作

c++ - 如何避免填充以使结构不使用额外的字节

c++ - 宏是强制内联的唯一方法吗

c++ - 如何使用 cv 和引用限定符从 std::function 获取参数和返回类型?

c++ - 传递捕获 unique_ptr 的 lambda

c++ - 使 yylex 返回 symbol_type 而不是 int