Victor
Victor

Reputation: 363

Class template in header

I have a class in which there are structures declared using template. Can't figure out how to describe class structure in the header file

.cpp file

#include <map>
#include <numeric>

class Statistics {
    private:
        std::map<int, int> *data;

        struct add_first {
            template<class Pair>
            int operator()(int value, const Pair& pair) const {
                return value + pair.first;
            }
        };

        struct add_second {
            template<class Pair>
            int operator()(int value, const Pair& pair) const {
                return value + pair.second;
            }
        };

        struct add_expectation {
            template<class Pair>
            int operator()(int value, const Pair& pair) const {
                return value + (pair.first * pair.second);
            }
        };

    public:
        Statistics(std::map<int, int> *load_data) {
            data = load_data;
        }

        double get_mean() {
            return std::accumulate((*data).begin(), (*data).end(), 0.0, add_first()) / (*data).size();
        }

        double get_expectation() {
            return std::accumulate((*data).begin(), (*data).end(), 0.0, add_expectation()) / std::accumulate((*data).begin(), (*data).end(), 0.0, add_second());
        }
};

In the header file I'm trying to write the following code .h file

#ifndef STATISTICS_H
#define STATISTICS_H

#include <map>

class Statistics {
    private:
        std::map<int, int> *data;
        struct add_first {
            template<class Pair>;
            int operator()(int value, const Pair& pair) const;
        };
        struct add_second {
            template<class Pair>;
            int operator()(int value, const Pair& pair) const;
        };
        struct add_expectation{
            template<class Pair>;
            int operator()(int value, const Pair& pair) const;
        };
    public:
        Statistics(std::map<int, int> *load_data);
        double get_mean();
        double get_expectation();
};

#endif

But under this definition, compiler generates an error that the identifier Pair is not defined. What's wrong?

Upvotes: 0

Views: 87

Answers (1)

scinart
scinart

Reputation: 466

After taking all suggentions by @Angew, there should be no error.

  1. remove extra colon.
  2. define class only in header files.

Upvotes: 1

Related Questions