template alike approach for floating point

M

mathieu

Hello,

I am trying to work around the issue with floating point as template
parameter. Basically all I want is be able to take advantage of the
compile time optimization. For instance how would one write something
like this with a single class declaration:

struct s_05
{
static const double TF = 0.5;
bool f(double v) { return v > TF; }
};

struct s_06
{
static const double TF = 0.6;
bool f(double v) { return v > TF; }
};
.... and so on and so forth

thanks !
-Mathieu
 
V

Victor Bazarov

mathieu said:
Hello,

I am trying to work around the issue with floating point as template
parameter. Basically all I want is be able to take advantage of the
compile time optimization. For instance how would one write something
like this with a single class declaration:

struct s_05
{
static const double TF = 0.5;
bool f(double v) { return v > TF; }
};

struct s_06
{
static const double TF = 0.6;
bool f(double v) { return v > TF; }
};
... and so on and so forth

You need to find a way (or ways) to express your constants without
simply specifying them. For example, if your constants can be
expressed as rationals, then you could define your 'TF' in terms
of integrals:

template<int over, unsigned under>
struct s_
{
static const double TF;
bool f(double v) { return v > TF; }
};

template<int over, unsigned under>
const double s_<over,under>::TF = double(over)/double(under);

typedef s_<5,10> s_05;
typedef s_<6,10> s_06;

int main() {
s_05 s1;
s_06 s2;

return s1.f(0.55) && s2.f(0.75);
}

V
 
M

mathieu

You need to find a way (or ways) to express your constants without
simply specifying them. For example, if your constants can be
expressed as rationals, then you could define your 'TF' in terms
of integrals:

template<int over, unsigned under>
struct s_
{
static const double TF;
bool f(double v) { return v > TF; }
};

template<int over, unsigned under>
const double s_<over,under>::TF = double(over)/double(under);

typedef s_<5,10> s_05;
typedef s_<6,10> s_06;

int main() {
s_05 s1;
s_06 s2;

return s1.f(0.55) && s2.f(0.75);
}

Pretty cool ! This should work for my limited usage.

Thanks !
-Mathieu
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top