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

By : Rjack
Source: Stackoverflow.com

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 {

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

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

There are a few error in here:


Your main should look like this:

int main() {
    AccumulatorMean<int> a;

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


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