Home > database >  C Generic Addition Method
C Generic Addition Method

Time:10-04

I have struct like this

template <typename T>
struct container
{
T norm() const
    {
        T sum = 0;
        for (unsigned int i = 0; i < length; i  )
        {
            sum  = value[i];
        }
        return sum;
    };
private:
    T *value{nullptr};
    unsigned int length{0};
};

I have a norm() method that adds all the values from the "value". I need to write this method so that it can add numbers and concatenate strings, characters. The question is that I do not understand how to determine what type of variable is passed and how to set the type for the "sum" I thought to determine the size of the first element and determine the type of the variable from it, but maybe there is a better method?

CodePudding user response:

To initialize a T, the way to do that in the template function is to use the brace-initializer:

T sum = {};

This will initialize sum to whatever the type T would be equal to if you default construct (for classes such as std::string) or value-initialize (for types such as int, double, etc.). For integer types, double, float, it is 0. For std::string it would be an empty string, etc.


After taking another look at your norm function, the following should also give the same results (not tested):

template <typename T>
T norm() const
{
    return std::accumulate(value, value   length, T{}, std::plus<T>());
}
  • Related