在模板中使用非虚拟调度
Use non-virtual dispatch in a template
我想调用一个虚拟的成员函数(在大多数地方使用继承来保持简单),但有时我想在性能关键的地方强制使用非虚拟调度来调用它,在这种地方,确切的类型是已知的编译时。我这样做是出于性能原因,在虚拟呼叫性能较差的平台上。对于大多数功能来说,虚拟功能的开销是可以的,但对于少数功能来说则不然。我希望避免将所有功能都复制为虚拟和非虚拟功能。
示例:
class Interface
{
public:
virtual void Do(){}
};
class Implementation: public Interface
{
public:
virtual void Do(){}
};
void DoIt(Interface &func)
{
func.Do();
};
int main()
{
Implementation a;
DoIt(a);
// can DoIt be constructed as a template to avoid virtual dispatch?
return 0;
}
如果你知道确切的类型,你可以这样做:
template <typename StaticType>
void DoIt(Interface &func)
{
static_cast<StaticType&>(func).StaticType::Do();
};
您需要手动向下转换到所需类型的位置(如果您确实知道类型,static_cast
也可以)。然后,您需要限定方法调用,禁用动态调度。
struct DerivedType : Interface {
virtual void Do() { std::cout << "Derived::Do" << std::endl; }
};
struct MostDerived : DerivedType {
virtual void Do() { std::cout << "MostDerived::Do" << std::endl; }
};
void processDerived( Interface & iface ) {
DoIt<DerivedType>( iface );
}
int main() {
MostDerived obj;
DoIt<Derived>( obj ); // Will call Derived::Do
}
请注意,使用限定名称将禁用动态调度,这意味着它不会被调度到对象的运行时类型,而是被调度到您让它调用的类型。
我认为您正在寻找一种能够实现静态多态性的奇怪递归模板模式(CRTP):
template <typename Derived>
class Base {
public:
virtual ~Base() {}
void foo() { Derived::func_in_derived(); }
};
class Derived : public Base<Derived> {
public:
void func_in_derived() {}
};
相关文章:
- 如何在c++中实现处理器调度模拟器
- 虚拟决赛作为安全
- PowerPC ppc64le上的Gcc Woverloaded虚拟错误
- 如何在C++中获得"静态纯虚拟"功能?
- C++无法定义虚拟函数 OUTER 类和头文件
- 用常见虚拟函数实现的任意组合来实现派生类的正确方法是什么
- 在模板基类中为继承类中的可选重写生成虚拟方法
- 尝试将unique_ptrs推送到向量时使用纯虚拟函数错误
- 有没有比在库中添加一个并非由所有派生类实现的新虚拟函数更好的设计实践
- 大小虚拟继承中的派生类
- 链接器找不到在虚拟类 c++ 中访问的静态字段的符号
- 使用 C++ 和 i2c 工具从虚拟 i2c 写入和读取
- 重载 -> shared_ptr 个实例中的箭头运算符<interface>,接口中没有纯虚拟析构函数
- 如果整个应用程序是虚拟映射的,为什么 new 会进行系统调用?
- 跨 DLL 边界访问虚拟方法是否安全/可能?
- 没有虚拟调度的默认方法实现
- 对于虚拟机,哪种调度方法更有效
- 如果在没有限定的情况下从构造函数/析构函数调用虚拟函数,则是否会发生虚拟调度
- C++类方法,可以使用虚拟调度或类似于没有对象上下文的静态函数来调用
- 在模板中使用非虚拟调度