Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

constexpr versus template, pow function

I am experimenting new feature of the c++11, constexpr especially. If I want to code a pow with template I will simply do:

//pow
template<class T, std::size_t n>
struct helper_pow{
    inline static T pow(T const& a){
        return a*helper_pow<T,n-1>::pow(a);
    }
};

//final specialization pow 
template<class T>
struct helper_pow<T,0>{
    inline static T pow(T const& a){
        return 1;
    }
};

Now if I call my function into my code simply by:

pow<double,5>(a) // where a is double

the corresponding assembly will be (gcc 4.8.0, -O2):

   movapd  %xmm0, %xmm1
    movsd   %xmm0, 24(%rsp)
    mulsd   %xmm0, %xmm1
    movq    %rbx, %rdi
    mulsd   %xmm0, %xmm1
    mulsd   %xmm0, %xmm1
    mulsd   %xmm0, %xmm1

Fine the code is inline.

If know I am looking the constexpr version, I have

template <class T>
inline constexpr T pow(T const& x, std::size_t n){
    return n>0 ? x*pow(x,n-1):1;
} 

The corresponding assembly is now:

    movsd   24(%rsp), %xmm2
    leaq    24(%rsp), %rdi
    movl    $4, %esi
    movsd   %xmm2, 8(%rsp)
    call    __Z3powIdET_RS0_m

where the function __Z#powIdET_RS0_m seems define by

LCFI1:
    mulsd   %xmm1, %xmm0
    movapd  %xmm0, %xmm2
    mulsd   %xmm1, %xmm2
    mulsd   %xmm2, %xmm1
    movapd  %xmm1, %xmm0
    ret

So do you have any idea why with constexpr the function is not inline and consider as "an external" function ? Does it exist a way to force the inline of a constexpr function ? Best.

like image 283
Timocafé Avatar asked Aug 20 '13 11:08

Timocafé


1 Answers

inline is nothing more than a hint for the compiler. It can do whatever it prefers. It exists compiler specific stuff like pragmas and __declspec to force on or off the inlining on a function.

May be the non const lvalue reference of the constexpr version interfers. You should just pass by value to a pow anyway.

like image 69
galop1n Avatar answered Oct 22 '22 05:10

galop1n