【问题标题】:Member function pointer to function object指向函数对象的成员函数指针
【发布时间】:2011-12-24 03:22:40
【问题描述】:

我有一个以函数指针为成员的类。在某些情况下,我希望该指针指向一个函数对象,这不可能吗?

class C {
public:
    C();
private:
    void (*p)();
    struct Functor {
        void operator()() {
        }
    };
};

C::C() : p(Functor()) {
}

int main(int argc, char **argv) {
    C c;
}

我明白了:

t.cpp: In constructor 'C::C()':
Line 12: error: cannot convert 'C::Functor' to 'void (*)()' in initialization

【问题讨论】:

  • 根据定义,没有。为什么您希望能够做到这一点?

标签: c++ functor member-function-pointers


【解决方案1】:

不,这是不可能的。 Functor 的类型甚至不接近 void(*)() 的类型。您可以将成员p 更改为Functor 类型,或者您可能正在寻找std::function

std::function 是一个通用的多态函数包装器。 std::function 的实例可以存储、复制和调用任何可调用的目标——函数、lambda 表达式、绑定表达式或其他函数对象。

【讨论】:

    【解决方案2】:

    不,Functor 对象不是函数指针。如果你想将 p 初始化为 Functor,你应该这样声明它:

    class C {
    public:
        C();
    private:
        struct Functor {
            void operator()() {
            }
        } p;
    };
    

    【讨论】:

      猜你喜欢
      • 2017-06-29
      • 2012-02-10
      • 2015-03-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多