I'm working on creating a library that averages integers. I'm running into a problem, though. When I try to compile my test code, the error states "invalid conversion from 'int' to 'int* (*)()'".
Here's the header file:
#ifndef Averaging_h
#define Averaging_h
#include "WProgram.h"
class AverageInteger
{
public:
AverageInteger(int (*functionInt()), unsigned int repeats);
int averageInt();
private:
int (*executeInt());
};
#endif
Here's the CPP file:
#include "Averaging.h"
//Constructor:
AverageInteger::AverageInteger(int (*functionInt()), unsigned int repeats)
{
executeInt() = functionInt();
int returnedInt = 0;
int answerInt = 0;
}
int AverageInteger::averageInt()
{
for (unsigned int i = 0; i < repeats; i++)
{
returnedInt = executeInt();
answerInt += returnedInt;
}
answerInt = (answerInt / repeats);
return answerInt;
}
Thanks for the help guys. I've added a few of the tips, but I'll save the rest for after I get the core of library working.
I've edited my library.
Averaging.h:
#ifndef Averaging_h
#define Averaging_h
#include "WProgram.h"
class Average
{
public:
Average(int* &functionInt(), unsigned int repeats);
long averageReading();
private:
int (*executeInt());
};
#endif
Averaging.cpp:
#include "Averaging.h"
//Constructor:
Average::Average(int* &functionInt(), unsigned int repeats)
{
executeInt() = &functionInt();
// int returnedInt = 0;
// int answerInt = 0;
if (repeats <= 0)
{
repeats = 1;
}
else
{
}
}
long Average::averageReading()
{
int returnedInt = 0;
long answerLong = 0;
for (unsigned int i = 0; i < repeats; i++)
{
returnedInt = executeInt();
answerInt += returnedInt;
}
answerInt = (answerInt / repeats);
return answerInt;
}
When I use this library, I get the error: "error: lvalue required as unary '&' operand"
There are quite a few syntax errors in there I'm afraid but more than that there is a fundamental problem with the approach. By trying to pass the address of a class member function you need to scope it to the owning class in the declaration of the function pointer which means you will never be able to pass anything other than a member of whatever class myCompass belongs to.
You could get around this by using a regular C function pointer, or have the data supplying function in a single-member base class but what you really need is a functor. Google it, it's been implemented many times before in countless C++ libraries.
I wrote this sample sketch which does what you're looking for, and copes with overflow into 64 bits (as long as the number of, and size of, the samples don't exceed 32 bits). You may not understand this code right away but it's worth persisting because the techniques are useful.
Thanks for your reply (and the example code!). I'll look into functors as soon as I can. I don't know when I'll have this library done, because of school, etc, but I'll post a link to it if/when I finish it.