模板类中的内联虚拟方法 [英] inline virtual method in template class

查看:221
本文介绍了模板类中的内联虚拟方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有get_p_pow方法的模板基类,该方法由foo函数调用:

I have a template base class with a get_p_pow method that is called by a foo function:

template <typename T_container> 
class base {    
    public:
    int foo() {
        ...
        get_p_pow(p_pow, delta_p);
        ...
    }

    ...

    protected:            
        virtual T_container& get_p_pow(T_container &p_pow, double delta_p) const {
            p_pow(0) = 1.0;
            p_pow(1) = delta_p;
            for (difference_type i = 2; i <= order; ++i) {
                p_pow(i) *= p_pow(i-1)*delta_p; 
            }

            return p_pow;
        }

    int order;
};   

对于某些派生类,order的值设置为特定数字,因此我可以展开循环,希望foo调用并内联展开版本:

For some derived classes, the value of order is set to a specific number, so I can unroll the loop, with the hope that foo calls and inlines the unrolled version:

template <typename T_container> 
class child : public base<T_container> {   
    ... 
    protected:            
        T_container& get_p_pow(T_container &p_pow, double delta_p) const {
            p_pow(0) = 1.0;
            p_pow(1) = delta_p;
            p_pow(2) = p_pow(1)*delta_p;
            p_pow(3) = p_pow(2)*delta_p;
            p_pow(4) = p_pow(3)*delta_p;
            p_pow(5) = p_pow(4)*delta_p;

            return p_pow;
        }
    // order set to 5 in constructor
};  

问题是,对于虚函数,我知道大多数时候它们无法内联,除非编译器具有该对象的特定实例,而不是该对象的指针/引用.但是,由于basechild是模板函数,因此它们位于头文件中,该头文件包含在使用这些类的每个翻译单元中.这意味着编译器应该知道支持内联所需的一切(据我所知,因为它不需要单独的编译).我已经尝试过了,基本上没有内联函数,也没有带来任何实际的性能好处(除了函数调用开销之外,我认为流水线也被破坏了).有没有办法支持这种情况的内联?还是有建议实施这种事情?

The problem is, is that I know for virtual functions, most of the time they cannot be inlined, unless the compiler has the specific instance of the object, and not a pointer/reference to it. However, since base and child are template functions, they are located in a header file which is included with every translation unit that uses these classes. That means the compiler should know everything it needs in order to support inlining (to my knowledge, since it does not need separate compilation). I've tried this out, and basically the function isn't inlined, and it doesn't lead to any real performance benefit (in addition to function call overhead, I think pipelining gets ruined too). Is there a way to support inlining for this situation? Or is there any advice to implement this kind of thing?

推荐答案

对于虚拟方法,内联没有任何实际意义(因为您需要运行时信息来确定用于内联的代码),因此编译器会生成正常"此类代码中的方法,并定期"调用它们.

In case of virtual methods inlining makes no real sense (as you would need runtime information do decide which code to use for inlining), so compilers generate "normal" methods out of such code, and call them "regularly".

这篇关于模板类中的内联虚拟方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆