相关疑难解决方法(0)

使用函数指针调用虚拟成员函数的基类定义

我想使用成员函数指针调用虚函数的基类实现.

class Base {
public:
    virtual void func() { cout << "base" << endl; }
};

class Derived: public Base {
public:
    void func() { cout << "derived" << endl; }

    void callFunc()
    {
        void (Base::*fp)() = &Base::func;
        (this->*fp)(); // Derived::func will be called.
                       // In my application I store the pointer for later use,  
                       // so I can't simply do Base::func().
    }
};
Run Code Online (Sandbox Code Playgroud)

在上面的代码中,func的派生类实现将从callFunc中调用.有没有办法可以保存指向Base :: func的成员函数指针,还是我必须以using某种方式使用?

在我的实际应用程序中,我使用boost :: bind在callFunc中创建一个boost :: function对象,我后来用它从程序的另一部分调用func.因此,如果boost :: bind或boost :: function有某种方法来解决这个问题也会有所帮助.

c++ virtual function-pointers boost-bind

19
推荐指数
1
解决办法
6129
查看次数

替换std :: function以将函数作为参数传递(回调等)

我在使用C++ 11进行实验时偶然发现了这一点.我发现它是一个明显的解决方案,但我还没有在野外找到任何其他的例子,所以我担心我会遗漏一些东西.

我所指的做法(在"addAsync"函数中):

#include <thread>
#include <future>
#include <iostream>
#include <chrono>

int addTwoNumbers(int a, int b) {
    std::cout << "Thread ID: " << std::this_thread::get_id() << std::endl;

    return a + b;
}

void printNum(std::future<int> future) {
    std::cout << future.get() << std::endl;
}

void addAsync(int a, int b, auto callback(std::future<int>) -> void) { //<- the notation in question
    auto res = std::async(std::launch::async, addTwoNumbers, a, b);

    if (callback) //super straightforward nullptr handling
        return callback(std::move(res));
}

int main(int argc, char** argv) {
    addAsync(10, 10, …
Run Code Online (Sandbox Code Playgroud)

c++ c++11

15
推荐指数
2
解决办法
2405
查看次数

指向成员的指针:指针值代表什么?

我正在使用指向成员的指针,并决定实际打印指针的值.结果不是我的预期.

#include <iostream>

struct ManyIntegers {

    int a,b,c,d;
};

int main () {

    int ManyIntegers::* p;

    p = &ManyIntegers::a;
    std::cout << "p = &ManyIntegers::a = " << p << std::endl; // prints 1

    p = &ManyIntegers::b;
    std::cout << "p = &ManyIntegers::b = " << p << std::endl; // prints 1

    p = &ManyIntegers::c;
    std::cout << "p = &ManyIntegers::c = " << p << std::endl; // prints 1

    p = &ManyIntegers::d;
    std::cout << "p = &ManyIntegers::d = " << p << …
Run Code Online (Sandbox Code Playgroud)

c++ pointers

9
推荐指数
2
解决办法
362
查看次数

将指向数据成员的指针转换为void*

我知道我可以获取指向类或结构的数据成员的指针,但是下面代码的最后一行无法编译:

struct abc
{
    int a;
    int b;
    char c;
};

int main()
{
    typedef struct abc abc;
    char abc::*ptt1 = &abc::c;
    void *another_ptr = (void*)ptt1;
}
Run Code Online (Sandbox Code Playgroud)

为什么我不能将ptt1转换为another_ptr?我们正在谈论指针,所以一个指针应该具有与另一个指针相似的尺寸(虽然在概念上不同)

c++ casting type-conversion pointer-to-member

6
推荐指数
1
解决办法
1197
查看次数