Using GSL Minimize in C++ - c++

I am having a problem with Minimization library in GSL. I am trying to implement the algorithm without derivatives, but in order to used i need to pass the function to minimize:
https://www.gnu.org/software/gsl/doc/html/multimin.html?highlight=minimization
I am following what they have there for the algorithm without derivatives, but when i try to used in my member class function: my_func i get this:
‘Class::my_func’ from type ‘double (Class::)(const gsl_vector*, void*)’ to type ‘double ()(const gsl_vector, void*)’
It seems the algorithm cannot use a member class function. My question is how to bypass this and transform the member class function into a normal (C like) function?

GSL uses params to pass arbitrary parameters into your function. Use a pointer to your object as "parameters".
Make a proxy function, a static member function in your class, which receives params. Inside this function, convert params to the proper type (pointer to your Class), and call the member function in it.
If your my_func is public, you can use a non-member ("global") proxy function.
class Class
{
double my_func(const gsl_vector*) // the real function
{
...
}
static double static_my_func(const gsl_vector* v, void* params) // proxy function
{
Class* object = static_cast<Class*>(params);
return object->my_func(v);
}
};
If your real function wants to receive additional parameters, you have to accommodate this somehow, e.g. making the parameters members of your Class, or (more complicated but more object-oriented) creating a temporary struct, which contains a pointer to your object and the additional parameters.

Related

Understand C++ const functions

I am new to c++ and im trying to write a simple c++ wrappers to integrate with this third party c++ library; which comes with bad documentation.
function to integrate with (this is all the documentation that came with this function):
virtual ImageCoord Raster::groundToImage(const XyzCoord & groundPt,
double desiredPrecision=0.001,
double* achievedPrecision=null) const
Text about function: This method converts the given groundPt (x,y,z in meters) to a returned image coordinate (line, sample in full image space pixels).
there is also some class documentation
Raster Class Ref
inherits from GeoModel
Public member functions:
virtual ImageCoord groundToImage (const XyzCoord &groundPt, double desiredPrecision=0.001, double *achievedPrecision=NULL) const =0
in my code i have:
//this is implemented correctly
const XyzCoord xyz(284971.17549099098, -126866.36533847413, 6350003.627515804)
double desiredPrecision = 0.000001;
double achievedPrecision = 0.0;
// not sure if this is what the documentation meant by "image coordinate" but it comes with the library
// ImageCoord(double line, double point)
ImageCoord imagePoints;
// the part im confused about, what is the proper way to invoke the above function, the below line was me trying out how to call the method
const Raster::groundToImage(&xyz, imagePoints);
Sorry for my ignorance in c++ but I've been baffled. I have lot of programing experience (8 plus years, just none with c++ so i understand programing terms, concepts and design patterns).
Im also trying to understand in the function defination what does this mean
const XyzCoord & groundPt
I was able to compile with
XyzCoord xyz(204971.17549099098, -106866.36533847413, 6350003.627515804);
Raster* service;
ImageCoord imagePoints = service->groundToImage(xyz); //segmentation error occurs on this line
but i then get a runtime error "Segmentation fault"
This is a non-static member function of a class named Raster.
You are supposed to invoke it via member access obj.groundToImage(/*args*/) where obj is an object of the class type to which the function belongs or a class type derived from that class.
Or, if the call happens inside another non-static member function of the same class or a derived class, it could just be groundToImage(/*args*/) which will call the function implicitly on the current object.
With virtual it may also be possible to invoke the function on an object of a base class of Raster, depending on where the virtual function has been declared first in the class hierarchy.
There are certain more specialized situations where a qualified call replacing groundToImage with Raster::groundToImage in either of the above could also be the intended behavior.
The const qualification of the function is irrelevant. It just means that the function can be called whether obj is const-qualified or not. Similarly the const-qualification on the function parameter is irrelevant. It just means that you can pass either a const- or non-const-qualified first argument. You don't have to make xyz const to be able to pass it. Only the other way around, passing a const-qualified expression to a non-const reference parameter is a problem. const is intended to signal that the function will not modify the argument and therefore doesn't care whether or not it is const-qualified.
const only makes sense when used in a declaration or type. Something like
const Raster::groundToImage(&ecef, imagePoints)
as a supposed function call doesn't make syntactical sense.
The function also expects up to three arguments of the specified types and returns a ImageCoord. You are not supposed to pass one as an argument. It is what the function returns.
The arguments should probably be xyz, desiredPrecision and &achievedPrecision given that you already declared them with the correct types.
It probably wants the last one as pointer because it is an out-parameter.
What the object on which the member function is called on is supposed to be is unclear from what you have shown. We don't know what ecef is though...
TL;DR:
ImageCoord imagePoint = someRasterObject.groundToImage(
xyz,
desiredPrecision,
&achivedPrecision
);
Or
ImageCoord imagePoint = somePointerToRasterObject->groundToImage(
xyz,
desiredPrecision,
&achivedPrecision
);
From the signature given:
virtual // A derived class's implementation of
// this function can be called via a
// pointer or reference to a parent
// class object
ImageCoord // This function returns an ImageCoord
// object
Raster:: // This is a member of the Raster class
groundToImage( // This function is named groundToImage
const XyzCoord & groundPt, // The first argument to this function is a
// reference to a constant XyzCoord
// object
double desiredPrecision=0.001, // The second argument is a double with a
// default value of 0.001 if not provided
double* achievedPrecision=null // The third argument is a pointer to a
// double with a default value of null if
// not provided
)
const // This function can be called on a
// constant Raster object
That means you need 2-4 things to call this function:
A (possibly const-qualified) Raster object to call the function on
An XyzCoord object to pass as the first parameter
(Optional) A double to pass as the second parameter
(Optional) A pointer to a double to pass as the third parameter
While nothing in your question explicitly states it, I would assume the function uses the 3rd parameter as an output. I would assume it writes the actually achieved precision to the double pointed to by the pointer you pass it, so you'll probably want to just pass it the address of a local double variable.
Each non-static method in a class is called on behalf of some object of that class (or some derived class), and the object is accessible within a method by an implicitly defined this pointer.
The const qualifier appended after the parameters' list of the method applies to that this value. In other words, it declares this of a type classname const* instead of classname*.
As a result the compiler will reject any attempts to modify the *this object from within the const-qualified method, so the method can be safely used on non-modifiable objects.
For example, the length() method of the std::string class is declared as
size_t length() const;
so when you use it like, say:
std:string s;
....
size_t len = s.length();
you can be sure the s variable will not be modified during calculation of len value.

Universal function pointer for classes [duplicate]

This question already has answers here:
C++ function pointer and member function pointer
(3 answers)
Closed 2 years ago.
typedef void (*funcPtrType)(); // function pointer type
map<char,funcPtrType>eventGroups;
void addSharedEvent(char groupIndex,void (*receiverFunc)() ){
if(groupIndex==0)
return;
eventGroups[groupIndex]=receiverFunc;
}
It works if adding inline functions but not if using non inlined class member functions like below...
void MainWin::uiValsUpdated()
{
}
void MainWin::test()
{
//invalid
wSync.addSharedEvent(4,&uiValsUpdated);
}
How to make universal pointer for accessing functions in various types of classes?
Alternatively could define class types also but still in universal manner like Qtˇs signals and slots for example.
typedef void (*funcPtrType)(); // function pointer type
Avoid obfuscating pointer types like this.
It works if adding inline functions but not if using non inlined class member
It has nothing to do inline vs non-inline, and everything to do with the fact that a function pointer cannot point to a non-static member function.
How to make universal pointer for accessing functions in various types of classes?
A function pointer can point to functions except non-static member functions as long as the prototype matches. To call such function, no class instance is required. Example:
void free_function() {}
auto fun_ptr = &free_function;
fun_ptr();
A pointer to member function can point to non-static member functions of a particular class with matching prototype. In order to call such pointed function, there must be an instance of the class. Example:
struct foo {
void member_function(){}
};
auto mem_fun_ptr = &foo::member_function;
foo f;
f.*mem_fun_ptr();
A function object can be used as a wrapper, and it can call any type of functions. If you want to call a member function, the needed instance can for example be stored as a member. A lambda is a shorthand for creating such function object. Example:
auto lambda_free = [] {
free_function();
}
auto lambda_member = [f] {
f.member_function();
}
lambda_free();
lambda_member();
Type erasure techniques can be used to hide the type of various function objects, since they can be called in the exactly same manner. Standard comes with a template for such purpose: std::function. Example:
std::function<void()> fun_wrapper;
fun_wrapper = lambda_free;
fun_wrapper = lambda_member;
fun_wrapper = fun_ptr;
//fun_wrapper = mem_fun_ptr; // nope; there is no instance of foo
Pointers to free functions are very different from those that point to member functions. Not only is the syntax different, member function pointers also need a this first argument - the instance of their class they are supposed to operate on. You cannot use the same map to store both, if you intend to deal with raw (member) function pointers.
One solution is some kind of type erasure; you can store std::function objects in your map:
map<char, std::function<void()>>eventGroups;
void addSharedEvent(char groupIndex, const std::function<void()>& callback){ ... }
You can construct the parameter by plain function pointers, and in case of member functions usage of std::bind or a lambda.

Function pointer to interface class function in child class constructor

I'm working on a project using interface based programming. The first part of this is for context just in case someone says I'm doing something completely wrong or has a different approach that fixes my issue.
I have a container class that includes several abstract interface classes. These define functions that return data I need.
This container class has a vector of parts that do not know about the container class, and therefore does not include the interface headers.
Every part is an object of the same type. When creating these objects, it passes a function pointer as an argument to the constructor of the child objects. This argument is a pointer to a function defined in one of the interface classes.
I'm trying to pass a pointer using &iTheInterfaceClass::theDataFunction to a constructor expecting U16(*pDataFunction)().
This results in the error
cannot convert 'U16 (iTheInterfaceClass::*)() {aka short unsigned int (iTheInterfaceClass::*)()}' to 'U16 (*)() {aka short unsigned int (*)()}' in initialization
If the parts include the .h file, I can get this to work, as I just match the prototype to include the namespace in the constructor. However, this breaks my abstraction. If each part includes a different interface, I have to create individual classes for each, even though the functionality is identical.
Is there anyway to get the prototypes to match without completely readjusting my strategy here?
As you've said yourself, your constructor expects the following type (excluding names):
U16 (*)()
However, you are trying to pass the following type:
U16 ( iTheInterfaceClass::* )()
Your constructor accepts free functions and class functions that are static, but you are trying to pass a non-static member function.They are not of the same type.
You could provide an overload for your constructor that takes in a member function as well as a reference or pointer to the object that the member function will be called on.
It could look something like:
public:
typedef U16( iTheInterfaceClass::*MemberFunctionPtr )();
MyContainer( iTheInterfaceClass& member, MemberFunctionPtr function ) : ... { ... }
Assuming you stored that information in some variables somewhere in the class, you could then call that function like so:
( member.*function )();
Where member is the variable that holds a reference to the object that you want to call the function on and function is the variable which holds the pointer to said member function.

c++ using method as parameters to functions

I don't understand why the following code compile and works:
template<typename Predicate>
void foo(Predicate p) {
}
bool g(int n) {
}
void user(int n) {
foo(g);
}
foo is supposed to get a function object that will run on a data structure but I made the method simpler, because what I don't understand is how can this works? A method isn't an object. The normal way to do it is to create a new class, override operator() and then send an instance of that class.
Well, in this case the Predicate parameter is substituted by a function pointer of type bool (*func) (int). Nothing wrong with that...
The Predicate template argument can be almost any type. So you can use it for function pointers and classes as well as the basic types.
If you use the function argument p as a function, then it can be anything that is callable, like a function pointer, an object whose class have an operator() member function, a pointer to a static member function, a std::bind object, a std::function object or a lambda expression.
It can't be a pointer to a member function though, because to call a pointer to a member function you need an instance to call it on. For this use std::bind.

Help needed in Use of Function pointer in C++

i have made a sample example, in this i'm trying to pass a function as argument i am getting error, could you please help me
typedef void (*callbackptr)(int,int);
class Myfirst
{
public:
Myfirst();
~Myfirst();
void add(int i,callbackptr ptr)
{
ptr(i,3);
}
};
class Mysec
{
public:
Myfirst first_ptr;
Mysec();
~Mysec();
void TestCallback()
{
callbackptr pass_ptr = NULL;
pass_ptr = &Mysec::Testing;
first_ptr.add(2,&Mysec::Testing);
}
void Testing(int a,int b)
{
int c = a+b;
}
};
The type of the callback function you're passing as parameter is not defined as part of a class. You probably should define Testing as static.
You are geting an error because you are pointing to a member function. Pointers to member functions are different. See here:
http://www.parashift.com/c++-faq-lite/pointers-to-members.html#faq-33.1
A member function needs to know what instance it is working with (the this pointer) so it can't be called like any other function. If you moved the callback function out of the class (or made it static, which is similar to moving it out of the class) you could call it like any other function.
A more modern way of doing this is to use functors, e.g. boost::function and something like boost::bind :
C++ Functors - and their uses
how boost::function and boost::bind work
Those can hide the difference between member and global functions.
You are trying to access a member function pointer here, using a simple function pointer typedef, which will not work. Let me explain.
When you write a normal, non-member function (similar to C), the function's code actually exists in a location indicated by the name of the function - which you would pass to a function pointer parameter.
However, in the case of a member function, all you have is the class definition; you don't have the actual instance of the class allocated in memory yet. In such a function, since the this pointer is not yet defined, any reference to member variables wouldn't make sense, since the compiler doesn't have enough information to resolve their memory locations. In fact, member function pointers are not exact addresses; they encode more information than that (which may not be visible to you). For more, read Pointers to Member Functions.