pack multiple c++ objects and pass to function [closed] - c++

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am using a c library to do integration, where the integrand is declared as fun(...,void *fdata,...)
which uses *fdata pointer to pass external variables, however, before doing numerical integration, I need to
interpolate the raw data using other c++ libraries, giving back some interpolating class objects,
basically I want to pass these objects to a integrand which is user-defined ...

You could use an structure and pass a pointer to it but it seems to me that you don't have a fixed number of objects to pass and therefore that an object aggregating others dynamically would suit better your needs so you can use a std::vector and pass its address as func fdata parameter.
An example:
#include <vector>
#include <iostream>
using namespace std;
class C //Mock class for your objs
{
public:
C(int x)
{
this->x = x;
}
void show()
{
cout << x << endl;
}
private:
int x;
};
void func(void *fdata) //Your function which will recieve a pointer to your collection (vector)
{
vector <C *> * v = (vector<C *> *)fdata; //Pointer cast
C * po1 = v->at(0);
C * po2 = v->at(1);
po1->show();
po2->show();
}
int main()
{
vector<C *> topass;
topass.push_back(new C(1)); //Create objects and add them to your collection (std::vector)
topass.push_back(new C(2));
func((void *)(&topass)); //Call to func
for(vector<C *>::iterator it = topass.begin(); it != topass.end(); it++)
delete(*it);
}

Related

Initializing an object as in a vector class [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 11 months ago.
Improve this question
So, I know a vector object can be declared and initialized like this:
// Nothing new here. I know <int> is a template
// and how to implement it:
vector <int> vect{ 10, 20, 30 };
I assume that the vector object has inside an array of values, and the functions of that class (like push_back() for example) manage it. I would like and have been trying to implement something like that in a class of my own, without success. Would be interesting being able to understand how it's done! Did many "experiments" but none worked.
// Random named class:
class A_Class
{
private:
// A pointer for the type I want:
int *A_pointer_To_int;
public:
// Trying to accept the input values between
// brackets and putting them inside a temp array:
A_Class(int Input_Array[]) {}
};
int main()
{
// trying to create the object like in the vector class.
// Returns error "No instance of constructor matches the argument list":
A_Class My_Object{1,2,3}
return 0;
}
In a function parameter, int Input_Array[] is just syntax sugar for a decayed pointer int* Input_Array, which does not provide any information about any array that may be passed in to it.
For what you are attempting, you need to accept a std::initializer_list instead, eg:
#include <initializer_list>
#include <algorithm>
// Random named class:
class A_Class
{
private:
// A pointer for the type I want:
int *A_pointer_To_int;
// the number of values in the array:
size_t size;
public:
A_Class(std::initializer_list<int> Input_Values) {
size = Input_Values.size();
A_pointer_To_int = new int[size];
std::copy(Input_Values.begin(), Input_Values.end(), A_pointer_To_int);
}
~A_Class() {
delete[] A_pointer_To_int;
}
};
int main()
{
A_Class My_Object{1,2,3}; // works now
return 0;
}
Online Demo

Custom reference type [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I am writing a wrapper around a C-API.
(i) Let capi_array_data capi_get_array(void) be a function contained within this library returning a struct containing metadata about a heap-allocated array managed by said API. It would look something like struct capi_get_array { size_t length; int* arr }; (using int for simplicity)
(ii) Such an array can be created by the user manually with malloc, new, std::vector, etc. It must then be registered with void capi_register_array(int*).
I want to make a wrapper class, call it MyArrayWrapper, managing such an array with the anatomy of an STL container, supporting operator[], begin, back, etc. In (i) this wrapper would not own the data, but in (ii) it would. My question now is, whether I should
(a) have one single class that can be constructed using either a std::initializer_list (or variadic template for that matter) or an int* returned by the API;
(b) have separate classes named something like MyArrayWrapperRef and MyArrayWrapper, the first handling (i) and the second handling (ii);
(c) optimally have the syntax MyArrayWrapper& for (i) and MyArrayWrapper for (ii); can this be done?
With (a) there could come up confusion, as one class does two things, which breaks the single-responsibility principle. Answers to questions like "does the copy constructor conduct a deep of shallow copy?" will not be obvious and would require further documentation.
(b) seems like a good choice, but now there are multiple cases: MyArrayWrapper, MyArrayWrapper&, MyArrayWrapperRef, MyArrayWrapperRef&. How would they differ? What about const references? This might even require another class MyArrayWrapperConstRef and again leads to confusion.
(c) is optimal and seems natural with other classes, but I don't know of a way to make it work. I could make a wrapper around capi_get_array returning a MyArrayWrapperRef, but I would have to save the source of the reference somewhere, right?
With (a) there could come up confusion, as one class does two things,
which breaks the single-responsibility principle.
You can also see it the other way around: The single responsibility of the wrapper is to hide the real ownership and who cleans up what.
Lets say you have this:
struct arr_data {
int* a;
unsigned size;
};
arr_data get_arr(){
arr_data ret;
ret.size = 5;
ret.a = new int[ret.size];
return ret;
}
void reg_arr(arr_data x){
static arr_data store = x;
}
Then a simple wrapper could look like this:
struct wrapper {
std::shared_ptr<arr_data> data;
// implement container-like interface
};
wrapper make_non_owning_wrapper() {
auto res = new arr_data();
*res = get_arr();
return { std::shared_ptr<arr_data>(res,[](arr_data* x){
std::cout << "delete x only\n";
delete x;
}) };
}
wrapper make_owning_wrapper() {
auto res = new arr_data();
res->size = 5;
res->a = new int[res->size];
return { std::shared_ptr<arr_data>(res,[](arr_data* x){
std::cout << "delete both\n";
delete[] x->a;
delete x;
})};
}
int main(){
auto v = make_owning_wrapper();
auto w = make_non_owning_wrapper();
auto z = v;
}
Using a shared pointer you can choose a) what to do on clean up and b) what happens when copying a wrapper without causing great confusion ;).

C++: struct accessing instance of itself [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I have come across a rather unusual issue in my code. A struct needs to be able to access instances of itself.
Relavent portion of code:
struct crtr {
char f;
void foo() {
for(int i=0; i<creatures[f].size(); i++) {/*code that accesses creatures[f][i]*/}
}
};
vector<crtr> creatures[10];
Of course, this is nowhere close to working - crtr.foo() requires creatures, while creatures requires crtr. Is there some way to initialize creatures before crtr, perhaps changing the vectors' data type? (preferably with minimal pointers, if possible)
I must be missing something, what's wrong with this?
struct crtr {
char f;
void foo();
};
vector<crtr> creatures[10];
void crtr::foo() {
for(int i=0; i<creatures[f].size(); i++) {/*code that accesses creatures[f][i]*/}
}
Also crtr::foo can be inline if that's required.
Use forward declaration of the struct:
struct crtr;
vector<crtr> creatures[10];
struct crtr {
char f;
void foo() {
for(int i=0; i<creatures[f].size(); i++) {/*code that accesses creatures[f][i]*/}
}
};

How to construct a complicated function pointer without typedef in C++? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
auto func(int (*(*pf)(int *)), int *p) -> int *(*)(int *)
{
cout << *(pf(p)) << endl;
return pf;
}//C++11 Standard
int *(*func2(int (*(*pf)(int *)), int *p))(int *)
{
cout << *(pf(p)) << endl;
return pf;
}//Before C++11 standard
This is a function that takes an int function pointer and an int pointer as it's parameter, and will return a int function pointer.
How to create a pointer for this function?
template<class T> using type=T;
template<class R, class...Args>
using sig=R(Args...);
typedef sig<int *(*)(int *) ,int (*(*)(int *)), int *>* pFun;
or
typedef
type<int *(*(int (*(*)(int *)), int *))(int *)>* pFun2;
Apply recursively, use using and/or typedef liberally.
In C++03, you can have ptr_to<X>::type which works.
Naturally this is silly, as you would really want to solve the problem with meaningful type names, rather than using template tomfoolery or wrangle K&R syntax.

c++ classes with parameters and comparisons [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
let's say i have a class of type human and i want to create a method function called jim.punch(billy); i created jim and i created billy. how do i refer to jim when i'm writing the function? let's say whatever returns is based on their weight. so if billy is bigger, something will happen and something else will happen if jim is bigger. i just don't know how to use jim in the function
#include <iostream>
using namespace std;
class dog
{
public:
int age;
int weight;
int height;
int punch(int);
};
int jim::punch(x)
{
if (jim > x) <------------------
{
return //something
}
else
{
return something
}
int main()
{
human jim;
jim.age = 30";
jim.weight = 175;
jim.height = 6;
human billy; //etc
jim.punch(billy);
return 0;
}
You should really follow a good book (or at least a good online tutorial); your question shows confusion about very basic C++ concepts.
Nevertheless, here's an answer to your particular situation (omitting loads of details and important-but-not-for-this-particular-case concepts). human is a class. Classes can have data members and member functions. Many instances (or obejcts) of a class type can exist; each of these has its own values of data members.
Each member function can access the members (data and functions) of the instance on which it was invoked. It can do so explicitly (using the keyword this which represents a pointer to the instance), or implicitly (just naming the data member).
So here's how you might express your situation in code:
class human
{
//place data members such as age, height, weight here
public:
int punch(const human &target);
};
int human::punch(const human &target)
{
std::cout << "PUNCH!";
if (weight > target.weight) //equivalent to this->weight > target.weight
{
return /* something which represents this object winning */
}
else
{
return /* something which represents target object winning */
}
//Note: you should handle == case as well
}
int main()
{
human jim, billy;
jim.punch(billy);
}