8

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?

rozzy
  • 2,828
  • 6
  • 25
  • 35

2 Answers2

18

(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?

Benjamin Lindley
  • 101,917
  • 9
  • 204
  • 274
  • This is going to be used in a spacecraft simulation and one of the requirements is that all parameters in a model shall be forcible so that one can easily simulate failures (for example forcing a measured temperature to zero or forcing the deployment angle of the solar array to a fixed value). These parameters will all be primitive types, hence the reason I want to restrict the types used in the template. – rozzy Dec 06 '13 at 09:17
  • Also, I used std::is_arithmetic instead of std::is_fundamental as I did not want to allow void and nullptr_t types – rozzy Dec 06 '13 at 10:35
  • @aero117: So, you don't want to allow someone to use an extended numeric type, like a 1024 bit floating point, or an unbounded rational number? – Benjamin Lindley Dec 06 '13 at 13:42
7

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.

masoud
  • 55,379
  • 16
  • 141
  • 208