I'm trying to pass an array of Coin objects to a Change function that is called from within a user interface function.
I have tried many combinations of * and & in different places and have found no success.
The user interface function header
void UserInterface (Coin Roll[])
The Change function header (tried Coin * coin and got expression must have class type errors)
bool Change ( Coin & coin, long int & mulah )
How I am trying to call Change (Roll is an array of Coins) within UserInterface
Change(Roll[j], mulah)
The whole program is here http://pastebin.com/6bsuyEvF
You can pass array as reference like below
void UserInterface (Coin (&Roll)[])
You have several possibilities
void UserInterface(Coin roll[], int size);
void UserInterface(Coin* roll, int size);
void UserInterface(Coin (&roll)[42]); // size should be 42
template <std::size_t N> void UserInterface(Coin (&roll)[N]);
Change the accepted type:
void UserInterface(std::vector<Coin>& roll);
void UserInterface(std::array<Coin, 42>& roll); // size should be 42
template <std::size_t N> void UserInterface(std::array<Coin, N>& roll);
There was no problem with the code!
I forgot to add '&' to the function prototype above int main()
bool Change ( Coin & coin, long int & mulah ) ;
int main()
{
Needed the address of operator.
Related
I'm using ROOT Cern to solve a multi-variable non-linear system of equations. For some problems I have 4 functions and 4 variables. However, for others I need 20 functions with 20 variables. I'm using a class called "WrappedParamFunction" to wrap the functions and then I add the wrapped functions to the "GSLMultiRootFinder" to solve them. The function is wrapped this way:
ROOT::Math::WrappedParamFunction<> g0(&f0, "number of variables", "number of parameters");
Therefore, I need to declare the f0...fi functions before my void main(){} part of the code. I'm declaring the functions in this way:
double f0(const double *x, const double *par){return -par[0]+y[0]*par[1];}
double f1(const double *x, const double *par){return -par[1]+y[1]*par[2];}
.
.
Is there a way to create those functions inside a loop and stack them in an array? Something like this:
double (*f[20])(const double *x, const double *par);
for(int i=0;i<20;i++){
f[i]= -par[i]+x[i]*par[i+1];
}
So that later I can wrap the functions in this way:
ROOT::Math::WrappedParamFunction<> g0(f[0], "number of variables", "number of parameters");
f[i]= -par[i]+x[i]*par[i+1];
You can't generate code at runtime, so you can't do exactly what you're asking for.
You can however save the value of i for use at runtime, so you have a single callable object with a hidden parameter i not passed explicitly by the caller. The simplest example is
auto f = [i](const double *x, const double *par)
{
return -par[i]+x[i]*par[i+1];
};
but this gives a unique type to the lambda f, so you can't easily have an array of them.
You can however write
using Callable = std::function<double, const double *, const double *>;
std::array<Callable, 20> f;
and store the lambdas in that.
I think you'll need to use ROOT::Math::WrappedParamFunction<Callable> for this to work, though, since the FuncPtr parameter type is not erased.
If you really can't change the WrappedParamFunction type parameter for whatever reason, you can generate a free function instead of a stateful lambda using templates - but it's pretty ugly.
Edit - I was considering writing that version out too, but fabian beat me to it. Do note that you have to either write out all that machinery for each distinct function that needs this treatment, wrap it in a macro, or generalize everything to take a function template parameter as well.
There are almost certainly better ways of accomplishing this, but this probably gets you closest to the desired result described in the question:
Create a function template with the offset as template parameter and then create an std::array of function pointers with function pointers pointing to specializations of a template function. Note that the size of the array must be a compile time constant for this to work:
template<size_t Offset>
double f(const double* y, const double* par)
{
return -par[Offset] + y[Offset] * par[Offset+1];
}
template<size_t ... Offsets>
std::array<double(*)(double const*, double const*), sizeof...(Offsets)> CreateFsHelper(std::index_sequence<Offsets...>)
{
return { &f<Offsets>... };
}
template<size_t N>
std::array<double(*)(double const*, double const*), N> CreateFs()
{
return CreateFsHelper(std::make_index_sequence<N>{});
}
int main()
{
auto functions = CreateFs<20>();
}
Making your i a template parameter and generating the functions recursively at compile time can also do the trick:
using FunctionPrototype = double(*)(const double *, const double *);
template<int i>
double func(const double * x, const double * par) {
return -par[i]+x[i]*par[i+1];
}
template<int i>
void generate_rec(FunctionPrototype f[]) {
f[i-1] = &func<i-1>;
generate_rec<i-1>(f);
}
template<>
void generate_rec<0>(FunctionPrototype f[]) { }
template<int i>
FunctionPrototype* generate_functions()
{
FunctionPrototype * f = new FunctionPrototype[i]();
generate_rec<i>(f);
return f;
}
FunctionPrototype * myFuncs = generate_functions<3>(); // myFuncs is now an array of 3 functions
"Is there a way to create an array of functions inside a loop in C or C++"
sure, you can create a std::array or std::vector of std::function.
You can also create a container of function pointers if you so desire.
I have written a function that takes in a dynamic length array but with fixed inner array size, the second parameter in the function is the length of the parent array. When I try to access the nested values however, I get the issue mentioned above.
void myFunc(int arrOfArr, int arrOfArrLen) {
// try to access
arrOfArr[0][1]; // expect val2
}
example usage
myFunc(
{
{val1, val2},
{val3, val4}
},
2
);
edit: I realize "contextually" obviously an integer has no indexes, but that's how you declare an array it seems...(truthfully in Arduino context) but apparently it's still C++
Here's a runable demo of above from the first sandbox Google returned
http://cpp.sh/5sp3o
update
I did find a solution, it's ugly but it works:
instead of passing in a "raw" nested array as a param, I set it as a variable first eg:
int arrOfArr[][3] = {
{val1, val2},
{val3, val4}
}
Then in the function I do the same thing
void myFunc(int arrOfArr[][3], int arrOfLen) {
// access
}
Call it
myFunc(arrOfArr, 2);
As I said it's ugly but works for me, this is a passing project thing not a low-level dev, maybe will learn it fully later on but not needed in day job.
edit: apparently the thing I was trying to do initially eg. embed an initializer list as a param does not work.
if you want to pass a nested array, the declaration may be:
template<size_t N>
void myFunc(int const arrOfArr[][N], int arrOfArrLen) {
// ...
}
and you can remove the template argument if N is already decided.
const size_t N = 3;
void myFunc(int const arrOfArr[][N], int arrOfArrLen) {
// ...
}
but it doesn't work if you pass a brace-enclosed initializer, you can add a overloaded function:
template<size_t M, size_t N>
void myFunc(int const (&arrOfArr)[M][N], int arrOfArrLen){
// attention: int *const*
// ...
}
I'm sort of new to C++ and programming in general. I'm making a pokemon remake of the old gameboy version for fun, and I'm having trouble passing a whole structure as an arguement.
This is a shortened version to highlight the problem I'm having:
struct Enemy_Pokeman
{
string opp_name;
int num_pokeman;
int pokeman_LVL;
};
void pl_Pokeman(Enemy_Pokeman);
void pokeman_data(string opp_name, int num_pokeman, int pokeman_ID[], int pokeman_LVL[],
int purpose)
{
Enemy_Pokeman enemypokeman[num_pokeman];
enemypokeman[0].opp_name = opp_name;
enemypokeman[0].num_pokeman = num_pokeman;
for(int i=0; i<num_pokeman; i++)
enemypokeman[i].pokeman_LVL = pokeman_LVL[i];
pl_Pokeman(enemypokeman); //Function call - Codeblocks detects error
//on this line
}
void pl_Pokeman(Enemy_Pokeman enemy)
{
cout << endl;
}
Sorry if this doesn't make sense, I didn't want to post the entire thing, so I chopped it up a bit.
The problem is that it won't accept Enemy_Pokeman as an arguement.
Function pl_Pokeman only takes Enemy_Pokeman type while you passed in an array of Enemy_Pokeman
You update pl_Pokeman function to take array as input:
void pl_Pokeman(Enemy_Pokeman enemy[], int arraySize);
Or
template<typename T, size_t N>
void pl_Pokeman(Enemy_Pokeman (&enemy)[N])
you're passing to your function whole array of Enemy_Pokemans, not just one element. function expects one element only. also, you're creating that array within a function, so it's a local variable. if function pokemon_data returns, that array will be destroyed.
For Single structure-
When you are passing the structure as a argument, you should pass with & operator.
pl_Pokeman(&enemypokeman); // Fix 1
While catching it you need to catch it with Structure pointer.
void pl_Pokeman(Enemy_Pokeman *); // Fix 2
For Array of structure-
pl_Pokeman(&enemypokeman,size); // pass it with size
while catching it
void pl_Pokeman(Enemy_Pokeman (*)[], int );
In my main function I create an array of objects of a certain class "Menu"
And when I call a function I want to provide a pointer to that array.
Menu menu[2];
// Create menu [0], [1]
Function(POINTER_TO_ARRAY);
Question: What is the correct way to write the Function parameters?
I try:
Function(&menu);
and in Header file:
void Function(Menu *menu[]); // not working
error: Cannot convert parameter 1 from Menu(*)[2] to Menu *[]
void Function(Menu * menu); // not working
error: Cannot convert parameter 1 from Menu(*)[2] to Menu *[]
and I can't come up with any other way to do this and I can't find a solution to this particular problem.
Simply, I want to be able to access the Menu array within the function through a pointer. What are the difference in normal pointer to a pointer to an array?
Declaration:
void Function(Menu* a_menus); // Arrays decay to pointers.
Invocation:
Function(menu);
However, you would need to inform Function() how many entries are in the array. As this is C++ suggest using std::array or std::vector which have knowledge of their size, beginning and end:
std::vector<Menu> menus;
menus.push_back(Menu("1"));
menus.push_back(Menu("2"));
Function(menus);
void Function(const std::vector<Menu>& a_menus)
{
std::for_each(a_menus.begin(),
a_menus.end(),
[](const Menu& a_menu)
{
// Use a_menu
});
}
Either by const or non-const pointer
void Function(Menu const* menu);
void Function(Menu* menu);
...or by const or non-const reference
void Function(Menu const (&menu)[2]);
void Function(Menu (&menu)[2]);
which can be generalized to a template so that the array size will be deduced by the compiler:
template<size_t N> void Function(Menu const (&menu)[N]);
template<size_t N> void Function(Menu (&menu)[N]);
Always call as Function(menu);
Should work if you use
void Function(Menu * menu);
and call using
Function(menu);
instead of
Function(&menu);
passing the array name causes it to decay to a pointer to the type contained in the array. However, as #hmjd says in his answer you will also need to pass the array size, so his suggestion of using a vector is favourable if this option is open to you.
You can use
Function((void *) whatever_pointer_type_or_array_of_classes);
in your main.
And in the function:
type Function(void * whatever)
{
your_type * x =(your_type *) whatever;
//use x
....
x->file_open=true;
....
}
This question is similar to what I'm trying to do Calling C++ member function pointer from a struct .
However my structure contains a member function pointer that is defined in a different class then the one the structure is defined and used in. Here is some example code of how my classes, structures and function pointers are laid out.
// Alpha.h:
class Alpha{
public:
void function1(char name[], int number);
void function2(char name[], int number);
void function3(char name[], int number);
typedef void (Alpha::*My_func_ptr)(char name[], int number);
static My_func_ptr functionTable[];
};
// Alpha.cpp:
#include "Alpha.h"
Alpha::My_func_ptr Alpha::functionTable[] = {
&Alpha::function1,
&Alpha::function2,
&Alpha::function3
};
void Alpha::function1(char name[], int number)
{
//some stuff
}
void Alpha::function2(char name[], int number)
{
//some stuff
}
void Alpha::function3(char name[], int number)
{
//some stuff
}
// Beta.h:
#include "Alpha.h"
typdef struct{
char bName[10];
Alpha::My_func_ptr fptr;
}ptr_structure;
class Beta{
public:
void betafunction();
Alpha alphaobject;
ptr_structure str_array[3];
};
// Beta.cpp:
#include "Beta.h"
void betafunction()
{
str_array[0].fptr = alphaobject.functionTable[0];
str_array[1].fptr = alphaobject.functionTable[1];
str_array[2].fptr = alphaobject.functionTable[2];
(str_array[0].fptr)("name", 1); //gives error expression must have
//(pointer-to-) function type
(this->*str_array[0].fptr)("name", 1);
//error pointer-to-member selection class types are incompatible "Beta" and "Alpha"
//sample function pointer call using function table from other class,
//this syntax compiles and runs without error.
(alphaobject.*Alpha::functionTable[0]("name", 1);
}
As you can see I can call the function pointer from an array, but can't seem to figure out how to call a function pointer from inside an array of structures.
When calling a through member function pointer, you need to have an instance of the object associated with that pointer:
(alphaobject.*(str_array[0].fptr))("name", 1)
^^^^^^^^^^^
I would think:
(object.*functionTable[0])(args, ...);
(objptr->*functionTable[0])(args, ....);
IIRC, the combination of object and the .* operator is like a big unary operator. So that has lower precedence to the [0] postfix. However, it also has lower prededence than the function call postfix operator (args, ...)
Analogy:
(*foo)(); /* classic C */
Of course the * operator is not required when calling a regular function. But if you do write it, you need the parens, because *foo() means something else.
You can go to one of two solutions, depending on how readable you want the code. The unreadable version (which might even be wrong, and I won't even try to compile):
void Beta::betafunction() {
Alpha a;
(a.*(strArray[0].fptr))("name",1);
}
But I would actually try to make things a bit simpler:
void Beta::betafunction() {
Alpha a;
Alpha::My_func_ptr mptr = strArray[0].fptr;
(a.*mptr)("name",1);
}
I believe the second to be much more readable, and the compiler can optimize away mptr pretty easily, so there is no point in trying to play guru with the syntax.