Reputation: 688
I have a class fp
which represents a fixed point number. The underlying type is fixed at compile time, the position of the decimal point is determined at runtime.
Thus I need to store the position p
of the decimal point somewhere.
Secondly, I want to use my fixed point number in structs which have variables of the fixed-point-number class fp
type, including arrays of it ( NB: I am using Cuda, thus, I cannot use std::vector). Since storing the position p
inside of the class fp
would yield a large overhead, I would like to store it inside of the container structs.
E.g. something like the following (which clearly does not compile)
template<int &p_> struct fp {
int data;
float get() { return data/(float)p_; }
void set( float data_ ) { data = data_*p_; }
};
struct container {
int p = 4;
fp<p> s;
};
I have the feeling that my approach is wrong, but I haven´t found another solution yet (I also have have no idea how to title my question --- feel free to edit it).
Upvotes: 0
Views: 299
Reputation: 179779
It looks like fp
is tied really closely to container
. I'd make that really explicit, and make fp
a nested type of container
. In C++, nesting a type does not create a special relation between instances. That relation between container
and fp
instances remains the member fp container::s
.
But you can now write container
accessors that wrap fp::get()
, adding fp::d
to the argument list of get
.
[edit] Since we'd need this in multiple classes, time for a bit of CRTP.
template <typename CT>
class baseContainer
{
protected:
struct fp {
int data;
float get(int p_) const { return data/(float)p_; }
void set( float data_, int p_ ) { data = data_*p_; }
};
float get(fp const& fp_) { return fp_.get((CT const*)(this)->p_); }
void set( fp& fp_, float data_) { fp.set(data, (CT*)(this)->p_); }
}
Now container
can inherit from baseContainer<container>
. In baseContainer<container>
, (CT*)(this)->p_
refers to container::p_
.
Upvotes: 1