我有这样一种情况,在这种情况下,我想要一个指向避免动态调度的虚函数的成员函数指针。如下所示:
struct Base
{
virtual int Foo() { return -1; }
};
struct Derived : public Base
{
virtual int Foo() { return -2; }
};
int main()
{
Base *x = new Derived;
// Dynamic dispatch goes to most derived class' implementation
std::cout << x->Foo() << std::endl; // Outputs -2
// Or I can force calling of the base-class implementation:
std::cout << x->Base::Foo() << std::endl; // Outputs -1
// Through a Base function pointer, I also get dynamic dispatch
// (which ordinarily I would want)
int (Base::*fooPtr)() = &Base::Foo;
std::cout << (x->*fooPtr)() << std::endl; // Outputs -2
// Can I force the calling of the base-class implementation
// through a member function pointer?
// ...magic foo here...?
return 0;
}出于好奇,我之所以要这样做,是因为派生类实现使用了一个实用程序类来记忆(添加缓存)基类实现。这个实用类接受一个函数指针,当然,函数指针会动态地分派给派生最多的类,这样我就会得到无限递归。
有没有一种语法可以让我通过函数指针重现我可以用x->Base::foo()实现的静态分派行为?
发布于 2015-04-21 16:11:50
您可以像这样强制对Base*进行切片:
std::cout << (static_cast<Base>(*x).*fooPtr)() << std::endl; // Outputs -1发布于 2015-04-21 16:24:42
你想要的属性没有独立的“成员函数指针”。与绑定成员函数最接近的是闭包:
Base * x = new Derived;
auto f = [x]() { x->Base::Foo(); }
f();如果您的类Base是一个特殊的、一次性的用例,并且在您的控制之下,那么您可能应该向它添加某种“接受访问者”函数,以便您可以动态地传递成员调用者,如x->accept(foo_caller);等。C++14中的一个示例:
struct X
{
template <typename F>
auto accept(F && f)
{
return [this, &f](auto &&... args) {
return f(this, std::forward<decltype(args)>(args)...); };
}
virtual void foo() const { std::cout << "base\n"; }
};用法:
void call_static_foo(X * p)
{
p->accept([](X * that){that->X::foo();});
}https://stackoverflow.com/questions/29766352
复制相似问题