I have a class that is basically a wrapper around a double that allows its value to be forced to a static value:
class ModelParameter
{
protected:
double val;
bool isForced;
double forcedVal;
public:
ModelParameter(void);
ModelParameter(double value);
double getValue(void);
void setValue(double value);
bool getIsForced(void);
void forceValue(double value);
void unforceValue(void);
};
But I want to be able to use it for any primitive types, not just doubles. If I redefine it like so:
template <class T>
class ModelParameter
{
protected:
T val;
bool isForced;
T forcedVal;
public:
ModelParameter(void);
ModelParameter(T value);
T getValue(void);
void setValue(T value);
bool getIsForced(void);
void forceValue(T value);
void unforceValue(void);
};
This would mean that any type could be used regardless if it is primitive or not. Is there any way I can restrict the types used in the template to use only primitive types?
(note: requires C++11)
#include <type_traits>
template <class T>
class ModelParameter
{
static_assert(std::is_fundamental<T>::value, "error message");
...
};
But why would you want to do this?
One way is explicit instantiation for your intended types. Move all implementations into the .cpp file and instantiate for those type:
.cpp file:
...
Definitions and implementation
....
class ModelParameter<float>;
class ModelParameter<int>;
...
Then, it just works for those types.
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