Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limiting C++ templates to primitive types

Tags:

c++

templates

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?

like image 929
rozzy Avatar asked Dec 05 '13 16:12

rozzy


2 Answers

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

like image 137
Benjamin Lindley Avatar answered Oct 11 '22 12:10

Benjamin Lindley


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.

like image 22
masoud Avatar answered Oct 11 '22 12:10

masoud