简体   繁体   English

模板类中的内联虚拟方法

[英]inline virtual method in template class

I have a template base class with a get_p_pow method that is called by a foo function: 我有一个带有get_p_pow方法的模板基类,该方法由foo函数调用:

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;
};   

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

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
};  

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. 但是,由于basechild是模板函数,因此它们位于头文件中,该头文件包含在使用这些类的每个翻译单元中。 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? 还是有建议实施这种事情?

在虚拟方法的情况下,内联没有实际意义(因为您需要运行时信息来确定用于内联的代码),因此编译器会从此类代码中生成“常规”方法,并“定期”调用它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM