简体   繁体   English

使用来自 object 的方法,使用 std::bind 和 std::function.target 调用 C 样式 function 地址

[英]Call a C-style function address with std::bind and std::function.target using a method from object

I have a C-style function, which stores another function as an argument.我有一个 C 风格的 function,它存储另一个 function 作为参数。 I also have an object, which stores a method that must be passed to the aforementioned function.我还有一个object,它存储了一个必须传递给前面提到的function的方法。 I built an example, to simulate the desired situation:我构建了一个示例,以模拟所需的情况:

#include <functional>
#include <iostream>

void foo(void(*f)(int)) {
    f(2);
}

class TestClass {
    public:
        std::function<void(int)> f;
        void foo(int i) {
            std::cout << i << "\n"; 
        }

};

int main() {

    TestClass t;
    t.f = std::bind(&TestClass::foo, &t, std::placeholders::_1);
    foo( t.f.target<void(int)>() );

    return 0;
}

What is expected is that it will be shown on screen "2".预期的是它将显示在屏幕“2”上。 But I'm having trouble compiling the code, getting the following message on the compiler:但我在编译代码时遇到问题,在编译器上收到以下消息:

error: const_cast to 'void *(*)(int)', which is not a reference, pointer-to-object, or pointer-to-data-member
        return const_cast<_Functor*>(__func);

As I understand the use of "target", it should return a pointer in the format void () (int), related to the desired function through std:: bind.据我了解“目标”的使用,它应该返回格式为 void () (int) 的指针,通过 std::bind 与所需的 function 相关。 Why didn't the compiler understand it that way, and if it is not possible to use "target" to apply what I want, what would be the alternatives?为什么编译器不这样理解它,如果不能使用“目标”来应用我想要的东西,还有什么替代方案? I don't necessarily need to use std:: function, but I do need the method to be non-static.我不一定需要使用 std::function,但我确实需要该方法是非静态的。

This is a dirty little hack but should work这是一个肮脏的小技巧,但应该可以

void foo(void(*f)(int)) {
    f(2);
}

class TestClass {
public:
    void foo(int i) {
        std::cout << i << "\n"; 
    }
};

static TestClass* global_variable_hack = nullptr;
void hacky_function(int x) {
    global_variable_hack->foo(x);
}


int main() {

    TestClass t;
    global_variable_hack = &t;
    foo(hacky_function);

    return 0;
}

//can also be done with a lambda without the global stuff
int main() {
    static TestClass t;
    auto func = [](int x) {
        t->foo(x); //does not need to be captured as it is static
    };
    foo(func); //non-capturing lambas are implicitly convertible to free functions
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM