c++在对象上调用特定类的虚函数
Call Virtual Function for Specific Class on Object in C++
我需要从类外部的某个对象上从"声明"类型调用函数。我做了一个小的代码样本,并把所需的行为作为注释,因为我不知道究竟如何问这个:)
template<typename T>
void hun(T* obj, class C* c)
{
//do some checking on c
if(some conditions from c are true)
{
//call fun from T ignoring it's virtual
}
}
struct A
{
virtual void fun(){};
virtual void gun(class C* c)
{
//do something specific to A
hun(this, c); //here call fun from A even if real type of this is B
};
}
struct B : public A
{
void fun(){};
void gun(class C* c)
{
//do something specific to B
hun(this, c);//here call fun from B even if real type of this is something derived from B
};
}
有可能实现这种行为吗?
我知道我可以使用A::fun()
或B::fun()
从类内部调用fun()
,但是hun()
的检查对所有类都是常见的,我不想用这个代码污染gun()
。
(这可能已经在其他地方回答过了…)
可以使用限定id显式调用虚函数的一次重写。成员函数的限定id的形式为my_class::my_function
。
参考,参见c++ Standard [expr.call]/1:
例子如果选择的函数是非虚函数,或者类中的id-表达式成员访问表达式是限定id,则调用该函数。否则,它的最终重写(10.3)在调用对象表达式的动态类型。
template<typename T>
void hun(T* obj, class C* c)
{
//do some checking on c
if(some conditions from c are true)
{
//call fun from T ignoring it's virtual
obj->T::fun(); // T::fun is a qualified-id
}
}
struct A
{
virtual void fun(){};
virtual void gun(class C* c)
{
//do something specific to A
hun(this, c); //here call fun from A even if real type of this is B
};
}; // note: semicolon was missing
struct B : public A
{
void fun(){};
void gun(class C* c)
{
//do something specific to B
hun(this, c);//here call fun from B even if real type of this is something derived from B
};
};
相关文章:
- 如何使用单独文件中的派生类访问友元函数对象
- 当使用透明的std函数对象时,我们还需要写空的尖括号吗
- 有没有办法将重载的类函数绑定到函数对象?
- 将指针传递到成员的指针,从模板参数包到函数对象
- 如何在类模板的成员函数中正确调用函数对象?正在生成 Visual Studio 编译器错误 C2440
- 隐式转换为比较函数对象(函子)用于 std::sort 而不是 std::map?
- C++使用函数对象的线程,如何调用多个析构函数而不是构造函数?
- 如何通过接口将函子分配给函数对象
- 对std::函数对象的调用不匹配,该对象是指向成员函数的指针
- 指向std::invoke中成员函数对象的指针
- 如何成功地将函数对象(或lambda)传递给trackbar回调的第二个参数(void*)
- "std::function"的简单版本:函数对象的生存期?
- C++ 将函数对象作为左值和/或右值传递
- SFINAE 用于具有默认参数的函数对象
- 构造函数对象赋值是否泄漏内存
- 如何发送通过绑定到函数/方法创建的函数对象?
- std::for_each 与函数对象
- 将函数对象传递给 std::function
- 访问执行策略for_each函数对象中的迭代器
- 通过C++函数对象类访问参数