I want to know if there is way/technique in the world of C++ template metaprogramming where I can substitue hard coded floating point coeffients. To make it clearer, I will try to give an example:
Consider that I want to make a method that solves linear equations:
y = a * x + b
One way is to supply a, x, b as arguments at runtime. This I want to avoid. Consider though that I know a and b then I could write something like:
double linear(double x) {
return 2.0 * x + 3.0;
}
So I know that a = 2.0, b= 3.0. What I want to do is to extract a and b from templates, so they are there at compile time, just as being hardcoded. An example method can look like (this is what I would like to write in my code):
template <class coefs>
double linear(double x) {
return coefs::a * x + coefs::b;
}
Is this possible somehow? Not sure either if my question is clear enough so let me know if I need to rephrase.
Since float and double types can't be template parameters, you'll can't set your coefficients via template parameters, but you can simply hard-code the values.
For instance, this won't work:
template<float a_in, float b_in>
struct coeff
{
static const float a = a_in;
static const float b = b_in;
};
linear<coeff<2.0, 3.0>>(4.0);
But this will:
struct coeff
{
static const float a = 2.0;
static const float b = 3.0;
};
linear<coeff>(4.0);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With