Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using const double* const as a template parameter - code perfomance question

I'm trying to understand the under the hood of using const double* const as template. I have some very basic calculation I want to perform efficiently and I don't know how the c++ compiler works(what is the assembly code).

The idea is to create a template for a function that get 3 constant doubles as template parameters and a double as an argument.

constexpr double p1 = 1;
constexpr double p2 = 2;
constexpr double p3 = 3;

template <const double* const a, 
        const double* const b, 
        const double* const c>
inline double func(double value)
{
    constexpr double d = *a - *b;
    constexpr double e = *a - *c;
    constexpr double ratio = d / e;
    constexpr double remain = *c - *a * ratio;

    return value * ratio + remain;
}

double func2(double c)
{
    return func<&p1,&p2,&p3>(c);
}

My question is if for every p1,p2,p3 the func< p1,p2,p3 >(c) will be compiled to c * < const value > + < const value >

or the compiler can't extract the const values in compilation time and the full function will execute in run time.

like image 567
M H Avatar asked Dec 08 '22 11:12

M H


1 Answers

When looking at the compiled output you can see that the compiler reduces func2 to a multiplication and an addition with two constants. It doesn’t even call func any more.

However, the compiler is perfectly capable of producing the same code without the need to muck around with non-type template arguments:

inline double func(
    double const a,
    double const b,
    double const c,
    double const value
) {
    double const d = a - b;
    double const e = a - c;
    double const ratio = d / e;
    double const remain = c - a * ratio;

    return value * ratio + remain;
}

This produces the exact same output.

like image 150
Konrad Rudolph Avatar answered Dec 09 '22 23:12

Konrad Rudolph