gpt4 book ai didi

c++ - std::bind 与来自父类的重载函数

转载 作者:太空狗 更新时间:2023-10-29 22:58:57 26 4
gpt4 key购买 nike

#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);

我想知道是否有任何方法可以通过 Derived 类绑定(bind) Base::f1(int)(绑定(bind) func6 在这里成功)。感谢您的帮助。

最佳答案

&Derived::Base::f1 代替 &Derived::f1 怎么样?

我是说

auto func6 = std::bind(static_cast<void(Derived::*)(int)const>(&Derived::Base::f1), std::cref(derived), std::placeholders::_1); 

根据 Oktalist 的建议(感谢),您还可以使用 &Base::f1

更简单。

关于c++ - std::bind 与来自父类的重载函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38559546/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com