Limiting C++ templates to primitive types

c++, templates

Solution

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

Problem

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?

Original source

Related problems