Assigning a null value to a generic type data member in a class

Viewed 194

I want to assign some sort of null value to a data member in my class. For int I can just use 0 but I don't know the type that will be used.

Here is my class definition

template <typename T>
class circular_buffer {

private:
    T arr [100] = {};
    int size = 0;
    T *first, *last;

public:
    circular_buffer(int s) : size(s), first(nullptr), last(nullptr)
    {}
    
    T* increment(T* ptr) {
        if (ptr == &arr[size-1])
            return &arr[0];
        else 
            return ++ptr;
    }
    
    void write(T data) {
        if (first == nullptr) {
            arr[0] = data;
            first = last = &arr[0];
        } else if (increment(last) == first) {
            throw std::domain_error("Must use overwrite() to overwrite last value in buffer");
        } else {
            last = increment(last);
            *last = data;
        } 
    }
    
    T read() {
        if (first == nullptr) {
            throw std::domain_error("No values in buffer");
        } else {
            T data = *first;
            *first = 0;
            if (first == last) {
                last = first = nullptr;
            } else {
                first = increment(first);
            }
            return data;
        }
    }
};

Inside of read() I assign *first to zero. Is there a standard way of doing this?

1 Answers

Only pointers can be set to nullptr. You should simply use the type's own default value, eg:

*first = T{};

If that is not an option, then define the array's element type as std::optional<T>, which you can set to std::nullopt, eg:

std::optional<T> arr [100];

...

T data = (first->has_value()) ? first->value() : T{};
*first = std::nullopt;
Related