c++templates

Default value for Template Class, C++


Is there a way to give a default value for a template class?

E.g. Say I have a class TimeSeries, that is templated. And I have a function called Foo() that returns T.

template <typename T>
class TimeSeries
{
    T foo();
}

I want Foo() to do some calculation and return something of type T. But in case it can't, I want it to give a default value. If T was double, I want that to be NaN. If T was int, I want that to be 0.

TimeSeries<double> t;
t.foo(); // returns NAN

TimeSeries<int> t;
t.foo(); // returns 0

How would I achieve that?

A bad solution is for Foo() to take in a default value.

template <typename T>
class TimeSeries
{
    T foo(T defaultValue)
    {
       T ret;
       // if OK
       ret = computeValue();
       // if not OK
       ret = defaultValue;
       return ret;
    }
}

So default value would be 0, or NaN, depending on the user.

Or am I asking for a flawed design in the first place?

EDIT - A logical question would be to ask what happens if T is not int or double. What does a default value even mean?

The way I'm using TimeSeries, T is not exactly a general purpose type. It could only be 1 of int, double, and string. I thought about simply writing 3 separate TimeSeries classes, but that seems like a flawed approach.

I'm open to other ideas.


Solution

  • You could declare the following template, default_value<>:

    template<typename>
    struct default_value;
    

    Then, provide full specializations for int and double with a member called value which provides the desired default value:

    template<>
    struct default_value<int> {
       static constexpr int value = 0;
    };
    
    template<>
    struct default_value<double> {
       static constexpr double value = NaN;
    };
    

    Then, in your foo function template, you can simply return that value:

    return default_value<T>::value;
    

    which will depend on T.