std::bind with overloaded function from parent class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | #include <iostream> #include <functional> class Base { public: virtual ~Base() {} virtual void f1() const {std::cout<<"Base::f1() called"<<std::endl;} virtual void f1(int) const {std::cout<<"Base::f1(int) called"<<std::endl;} virtual void f2() const {std::cout<<"Base::f2() called"<<std::endl;} }; class Derived : public Base { public: virtual ~Derived() {} void f1() const {std::cout<<"Derived::f1() called"<<std::endl;} }; int main() { Base base; Derived derived; auto func1 = std::bind(static_cast<void(Base::*)()const>(&Base::f1), std::cref(base)); func1(); auto func2 = std::bind(static_cast<void(Derived::*)()const>(&Derived::f1), std::cref(derived)); func2(); auto func3 = std::bind(&Base::f2, std::cref(base)); func3(); auto func4 = std::bind(&Derived::f2, std::cref(derived)); func4(); auto func5 = std::bind(static_cast<void(Base::*)(int)const>(&Base::f1), std::cref(base), std::placeholders::_1); func5(1); auto func6 = std::bind(static_cast<void(Derived::*)(int)const>(&Derived::f1), std::cref(derived), std::placeholders::_1); // error line func6(2); return 0; } |
当我试图建立以上代码,GCC提供下面的错误消息。
test.cpp:34:80: error: invalid static_cast from type ‘void
(Derived::)() const’ to type ‘void (Derived::)(int) const’auto func6 = std::bind(static_cast(&Derived::f1),
std::cref(derived), std::placeholders::_1);
"我想知道有什么方法可以用在这类
用
我的意思是
1 | auto func6 = std::bind(static_cast<void(Derived::*)(int)const>(&Derived::Base::f1), std::cref(derived), std::placeholders::_1); |
如Oktalist所建议(谢谢),您也可以使用
更简单。