C++: run-time error from a template class

By : Rjack
Source: Stackoverflow.com
Question!

Hi guys I have a problem with my program. I'm new with c++ and I'm trying to code generic programming but, as usual, I have a lot of errors from my program. I'm trying my very best but I don't understand where my error is. I want a template class where i describe a method add() that take a sum, the c'tor and compute() which make an arithmetic average of sum. nAdd is the number of element. thank you very much!

template<typename T>
class AccumulatorMean {
    public:

        AccumulatorMean() : sum(0), nAdd(0), media(0) {};
        T add(const T& data);
        T compute();
private:
        int nAdd;
        T sum;
        T media;
};

template <typename T>
T& AccumulatorMean::add(const T& data) {
    sum += data;
    nAdd++;
    return sum;
}
template <typename T>
T& AccumulatorMean::compute() {
    media = sum/nAdd;
    return media;
}
int main() {
    AccumulatorMean a;
    a.add<int>(5);
}
By : Rjack


Answers
There are a few error in here:

First:

Your main should look like this:

int main() {
    AccumulatorMean<int> a;
    a.add(5);
}

You specified the class to have a template parameter. So you have to add it when you instantiate the class.

Second:

When you define the member functions of a class with a template param this has to be added too:

template <typename T>
T AccumulatorMean<T>::add(const T& data) {
    ...
}

See the AccumulatorMean<T>

And third:

In your code the definitions of the functions returned T& while you declared them to return T. That was also wrong. I already changed this above in my code.

By : Hayt


This video can help you solving your question :)
By: admin