I have many calls to a function that takes just one argument and I don't want update those calls. But I want to call that function from some other special place but in that case it should additionally fill a vector that I will pass with some data.
I know I can create a default argument with NULL pointer to a std::vector container and then, if it is null, skip doing any extra actions and if it is a valid pointer - gather data to vector. However I wanted to try using boost::optional.
Please see the code below. It compiles and works, but Is this approach fine or I shouldn't do that and better use raw pointer?
#include <boost/optional.hpp>
#include <boost/none_t.hpp>
#include <vector>
//header file declaration
int doAction(
int value,
char *msg = NULL,
boost::optional<std::vector<int>&> optionalNumberVec = boost::none);
//main.cpp
int doAction(int value, char* msg, boost::optional<std::vector<int>&> optionalNumberVec)
{
//do main actions here
//...
//...
//end of main action
//get additional information to table
if (optionalNumberVec)
{
optionalNumberVec.get().push_back(5);
optionalNumberVec.get().push_back(3);
}
return 1;
}
int main()
{
std::vector<int> numVec;
boost::optional<std::vector<int>&> optionalNumberVec(numVec);
doAction(2);
doAction(2, NULL, optionalNumberVec);
return 0;
}
Using boost or not is a simple decision based on your preferences (or your boss's preferences).
Once you get used to C++ you will notice that it doesn't really matter which one you use, as long you know how to use them.
Related
I'm trying to build a tree-like structure in C++ and I found out about initializer_list and tried to implement it as part of my code. I want the code to be able to create an object from a set of properties, be able to apply some methods and then append at the end an array of children.
So I came up (after a lot of tries and failure) with this:
#include <vector>
#include <initializer_list>
struct Branch
{
// Branch properties
int val;
std::vector<Branch> data;
Branch(int i): val(i) {}
Branch& operator=(std::initializer_list<Branch> list)
{
data = list;
return *this;
}
// Some function with specific behaviour
Branch& bar() {
return *this;
}
};
int main()
{
auto Main = Branch(1).bar() = {
Branch(2) = {
Branch(4)
},
Branch(3).bar(),
};
return Main.val;
}
As you can see, in my code I first pass the int property and then (sometimes) call a function depending on whether I want some specific traits for that branch or not. Then I attach a list for its children.
Now, I know that there are probably many things wrong with my code. For once I wanted to pass "Branch&" as type to the initializer_list (and vector) so it does not create a copy but then the compiler said no operator "=" matches these operands inside the main function.
So, here is my question. Is there a way to solve this? Maybe a workaround to pass a reference... Or maybe another implementation with similar effects.
I also tried with std::array instead of vector but it seems like they are not compatible.
I'm new to C++ and having a bit of trouble with accessing variables inside a class. From what I've read on here so far creating globals is a really bad practice and not to do that, but I dont know how else to move access to a class around.
So far my searches have pointed me to set and get functions in the class, but I think I can only use them in the block where the object is defined.
Basically what I want to know is if I define a class object in main() then call a function in main like gameLoop() how do I access that object inside that new function without making the class object global.
For instance:
#include "stdafx.h"
#include <iostream>
using namespace std;
#include <string>
class Word
{
private:
string m_word;
int m_length;
public:
void set(string word, int length)
{
m_word = word;
m_length = length;
}
};
void gameLoop()
{
word1.set(); //flags error as it cant acces the word1 object
//I want to be able to access word1 from here
//Not a copy because that wouldnt change the actual word1
//I dont want to define it in here because then it would be created again
//for each loop of gameLoop
}
int main()
{
Word word1;
int play = 1;
while (play ==1){
gameLoop();
}
return 0;
}
This is a largely simplified version but for the purpose of the game I want the class to be stored externally but for a number of gameplay functions inside gameLoop to be able to access and change the class object.
Ideally, the dependencies of a function should be stater in the parameter list. If your gameLoop function requires a Word object, pass it in as an argument. That way, it's clear what objects the function requires to work. This would look something like:
void gameLoop(Word& word)
{
word.set();
// ^ Obviously you need to supply args here.
}
int main()
{
Word word1;
int play = 1;
while (play ==1){
gameLoop(word1);
}
return 0;
}
And since you're mutating the Word object in the function, you need to pass it by reference, or else you're just modifying a copy.
Your only other sane option would be to make the word object global, but that should be avoided at all costs. It makes testing more difficult since you need to take into consideration every change that may have happened, which makes it difficult to isolate problems.
If you're structuring you're program this way, you would have to pass it as a parameter to gameloop
However, This is a very poor design, since anything you create in main and want to access in gameloop would have to be passed in as an argument. I would consider a different approach.
You could move the entire loop and variable declarations into gameLoop as so:
void gameLoop()
{
Word word1;
int play = 1;
while (play ==1){
word1.set(/*args*/);
}
}
int main()
{
gameLoop();
return 0;
}
This way you won't have to pass a million things into gameloop. Generally in games there's some initialization and finalization that needs to take place as well, and this can all be done in main before/after the call to gameLoop.
So to answer you original question, you would have to pass word1 as an argument to gameLoop(). So redefine your function to accept a Word argument, and then pass in word1. but again, I would reconsider your current design before its too late
Suppose I want to implement a simple abstraction over pthreads.
(or any C API that takes function pointers for callbacks or threads).
Like std::thread, I want the interface to be able to take function objects in general.
How do I bridge the gap in a way that works for all cases?
(That includes binds, lambda functions, etc.)
I know about the std::function::target but afaik, it does not do what I need.
If the API takes functions with a void* for user data as, e.g., pthread_create() does, you'd pass a pointer to the function as user data, call a trampoline which casts the user data to your function type, and calls the function. For example:
#include <functional>
#include <pthread.h>
extern "C" void* trampoline(void* userData) {
return (*static_cast<std::function<void*()>*>(userData))();
}
void* start() {
// ...
return 0;
}
int main() {
pthread_t thread;
std::function<void*()> entry(start);
pthread_create(&thread, 0, &trampoline, &entry);
// ...
}
The immediate implication is, however, that the function object life-time isn't easily controlled. In the example above the std::function<void*()> object happens to live long enough but it isn't always as easy.
If the function you try to call doesn't have a user data argument, you are pretty much out of luck. You might get away with using global objects but it is almost certainly a rather fragile approach.
A lambda function can be used anywhere that takes regular function pointers. In other words, it can be used wherever you would use regular functions/pointers to functions..
Example: https://ideone.com/4CJjlL
#include <iostream>
void voidfunc(void (*func_ptr)(void))
{
func_ptr();
}
void funcwithargs(void (*func_ptr)(int, char, std::string), int a, char b, std::string c)
{
func_ptr(a, b, c);
}
int main()
{
auto vf = []{std::cout<<"Called void func..\n";};
auto vfwa = [](int a, char b, std::string c) {std::cout<<"Called func with args with: "<<a<<b<<" "<<c<<"\n";};
voidfunc(vf);
funcwithargs(vfwa, 10, 'x', " + 3");
return 0;
}
Likewise, you can use std::function instead of the function pointer..
I would like to do something like:
for(int i=0;i<10;i++)
addresses[i] = & function(){ callSomeFunction(i) };
Basically, having an array of addresses of functions with behaviours related to a list of numbers.
If it's possible with external classes like Boost.Lambda is ok.
Edit: after some discussion I've come to conclusion that I wasn't explicit enough. Please read Creating function pointers to functions created at runtime
What I really really want to do in the end is:
class X
{
void action();
}
X* objects;
for(int i=0;i<0xFFFF;i++)
addresses[i] = & function(){ objects[i]->action() };
void someFunctionUnknownAtCompileTime()
{
}
void anotherFunctionUnknowAtCompileTime()
{
}
patch someFunctionUnknownAtCompileTime() with assembly to jump to function at addresses[0]
patch anotherFunctionUnknownAtCompileTime() with assembly to jump to function at addresses[1]
sth, I don't think your method will work because of them not being real functions but my bad in not explaining exactly what I want to do.
If I understand you correctly, you're trying to fill a buffer with machine code generated at runtime and get a function pointer to that code so that you can call it.
It is possible, but challenging. You can use reinterpret_cast<> to turn a data pointer into a function pointer, but you'll need to make sure that the memory you allocated for your buffer is flagged as executable by the operating system. That will involve a system call (LocalAlloc() on Windows iirc, can't remember on Unix) rather than a "plain vanilla" malloc/new call.
Assuming you've got an executable block of memory, you'll have to make sure that your machine code respects the calling convention indicated by the function pointer you create. That means pushing/popping the appropriate registers at the beginning of the function, etc.
But, once you've done that, you should be able to use your function pointer just like any other function.
It might be worth looking at an open source JVM (or Mono) to see how they do it. This is the essence of JIT compilation.
Here is an example I just hacked together:
int func1( int op )
{
printf( "func1 %d\n", op );
return 0;
}
int func2( int op )
{
printf( "func2 %d\n", op );
return 0;
}
typedef int (*fp)(int);
int main( int argc, char* argv[] )
{
fp funcs[2] = { func1, func2 };
int i;
for ( i = 0; i < 2; i++ )
{
(*funcs[i])(i);
}
}
The easiest way should be to create a bunch of boost::function objects:
#include <boost/bind.hpp>
#include <boost/function.hpp>
// ...
std::vector< boost::function<void ()> > functors;
for (int i=0; i<10; i++)
functors.push_back(boost::bind(callSomeFunction, i));
// call one of them:
functors[3]();
Note that the elements of the vector are not "real functions" but objects with an overloaded operator(). Usually this shouldn't be a disadvantage and actually be easier to handle than real function pointers.
You can do that simply by defining those functions by some arbitrary names in the global scope beforehand.
This is basically what is said above but modifying your code would look something like this:
std::vector<int (*) (int)> addresses;
for(int i=0;i<10;i++) {
addresses[i] = &myFunction;
}
I'm not horribly clear by what you mean when you say functions created at run time... I don't think you can create a function at run time, but you can assign what function pointers are put into your array/vector at run time. Keep in mind using this method all of your functions need to have the same signature (same return type and parameters).
You can't invoke a member function by itself without the this pointer. All instances of a class have the function stored in one location in memory. When you call p->Function() the value of p is stored somewhere (can't remember if its a register or stack) and that value is used as base offset to calculate locations of the member variables.
So this means you have to store the function pointer and the pointer to the object if you want to invoke a function on it. The general form for this would be something like this:
class MyClass {
void DoStuf();
};
//on the left hand side is a declaration of a member function in the class MyClass taking no parameters and returning void.
//on the right hand side we initialize the function pointer to DoStuff
void (MyClass::*pVoid)() = &MyClass::DoStuff;
MyClass* pMyClass = new MyClass();
//Here we have a pointer to MyClass and we call a function pointed to by pVoid.
pMyClass->pVoid();
As i understand the question, you are trying to create functions at runtime (just as we can do in Ruby). If that is the intention, i'm afraid that it is not possible in compiled languages like C++.
Note: If my understanding of question is not correct, please do not downvote :)
Think of your basic GLUT programs. They simply run from a main method and contain callbacks like `glutMouseFunc(MouseButton) where MouseButton is the name of a method.
What I have done is I have encapsulated the main file into a class, so that MouseButton is no longer a static function but has an instance. But doing this gives me a compilation error :
Error 2 error C3867: 'StartHand::MouseButton': function call missing argument list; use '&StartHand::MouseButton' to create a pointer to member c:\users\angeleyes\documents\visual studio 2008\projects\capstone ver 4\starthand.cpp 388 IK Engine
It is not possible to provide a code sample as the class is quite huge.
I have tried using this->MouseButton but that gives the same error. Can't a pointer to an instance function be given for callback?
As the error message says, you must use &StartHand::MouseButton syntax to get a pointer to a member function (ptmf); this is simply mandated as part of the language.
When using a ptmf, the function you are calling, glutMouseFunc in this case, must also expect to get a ptmf as a callback, otherwise using your non-static MouseButton won't work. Instead, a common technique is for callbacks to work with a user-supplied void* context, which can be the instance pointer—but the library doing the callbacks must explicitly allow this parameter. It's also important to make sure you match the ABI expected by the external library (the handle_mouse function below).
Since glut doesn't allow user-supplied context, you have to use another mechanism: associate your objects with glut's current window. It does provide a way to get the "current window", however, and I've used this to associate a void* with the window. Then you simply need to create a trampoline to do the type conversion and call the method.
Machinery:
#include <map>
int glutGetWindow() { return 0; } // make this example compile and run ##E##
typedef std::pair<void*, void (*)(void*,int,int,int,int)> MouseCallback;
typedef std::map<int, MouseCallback> MouseCallbacks;
MouseCallbacks mouse_callbacks;
extern "C" void handle_mouse(int button, int state, int x, int y) {
MouseCallbacks::iterator i = mouse_callbacks.find(glutGetWindow());
if (i != mouse_callbacks.end()) { // should always be true, but possibly not
// if deregistering and events arrive
i->second.second(i->second.first, button, state, x, y);
}
}
void set_mousefunc(
MouseCallback::first_type obj,
MouseCallback::second_type f
) {
assert(obj); // preconditions
assert(f);
mouse_callbacks[glutGetWindow()] = MouseCallback(obj, f);
//glutMouseFunc(handle_mouse); // uncomment in non-example ##E##
handle_mouse(0, 0, 0, 0); // pretend it's triggered immediately ##E##
}
void unset_mousefunc() {
MouseCallbacks::iterator i = mouse_callbacks.find(glutGetWindow());
if (i != mouse_callbacks.end()) {
mouse_callbacks.erase(i);
//glutMouseFunc(0); // uncomment in non-example ##E##
}
}
Example:
#include <iostream>
struct Example {
void MouseButton(int button, int state, int x, int y) {
std::cout << "callback\n";
}
static void MouseButtonCallback(
void* self, int button, int state, int x, int y
) {
static_cast<Example*>(self)->MouseButton(button, state, x, y);
}
};
int main() {
Example obj;
set_mousefunc(&obj, &Example::MouseButtonCallback);
return 0;
}
Notice that you don't call glutMouseFunc directly anymore; it is managed as part of [un]set_mousefunc.
Just in case it isn't clear: I've rewritten this answer so it should work for you and so that it avoids the C/C++ linkage issue being debated. It will compile and run as-is (without glut), and it should work with glut with only minor modification: comment or uncomment the 4 lines marked ##E##.
No, a pointer to an instance function can not be given to a callback function expecting a function pointer of a certain signature. Their signatures are different. It won't compile.
Generally such APIs allow you to pass in a void* as a "context" parameter. You pass in your object there, and write a wrapper function which takes the context as the callback. The wrapper casts it back to whatever class you were using, and calls the appropriate member function.
You can't replace a static callback with an instance one. When the caller calls your callback, on what instance whoul it call? In other words, how does the caller pass in the formal 'this' argument?
The solution is to have a static callback stub and pass the instance as argument, which implies the callee must accept an arbitrary pvoid that will pass back when invoking the callback. In the stub, you can then call the non-static method:
class C {
void f() {...}
static void F(void* p) {
C* pC = (C*)p;
pC->f();
}
}
C* pC = ...;
someComponent.setCallback(&C::F, pC);
Contrary to what everyone seems to be saying, you most definitely CAN use a non-static member function as a callback method. It requires special syntax designed specifically for getting pointers to non-static members, and special syntax to call that function on a specific instance of a class. See here for a discussion of the needed syntax.
Here is sample code that illustrates how this works:
#include <cstdlib>
#include <string>
#include <iostream>
#include <vector>
#include <sstream>
#include <algorithm>
using namespace std;
class Operational
{
public:
Operational(int value) : value_(value) {};
string FormatValue() const ;
private:
int value_;
};
string Operational::FormatValue() const
{
stringstream ss;
ss << "My value is " << value_;
return ss.str();
}
typedef string(Operational::*FormatFn)() const; // note the funky syntax
Operational make_oper(int val)
{
return Operational(val);
}
int main()
{
// build the list of objects with the instance callbacks we want to call
Operational ops[] = {1, 2, 3, 5, 8, 13};
size_t numOps = sizeof(ops)/sizeof(ops[0]);
// now call the instance callbacks
for( size_t i = 0; i < numOps; ++i )
{
// get the function pointer
FormatFn fn = &Operational::FormatValue;
// get a pointer to the instance
Operational* op = &ops[i];
// call the callback on the instance
string retval = (op->*fn)();
// display the output
cout << "The object # " << hex << (void*)op << " said: '" << retval << "'" << endl;
}
return 0;
}
The output of this program when I ran it on my machine was:
The object # 0017F938 said: 'My value is 1'
The object # 0017F93C said: 'My value is 2'
The object # 0017F940 said: 'My value is 3'
The object # 0017F944 said: 'My value is 5'
The object # 0017F948 said: 'My value is 8'
The object # 0017F94C said: 'My value is 13'
You cannot use a non-static member function in this case.
Basically the type of the argument expected by glutMouseFunc is
void (*)(int, int, int, int)
while the type of your non-static member function is
void (StartHand::*)(int, int, int, int)
First problem is that types don't really match.
Second, in order to be able to call that method, the callback would have to know which object ( i.e. "this" pointer ) your method belongs to ( that's pretty much why the types are different in the first place ).
And third, I think you're using the wrong syntax to retrieve the method's pointer. The right syntax should be: &StartHand::MouseButton.
So, you have to either make that method static or use some other static method that would know which StartHand pointer to use to call MouseButton.
The following works in c++ to define a c callback function, useful for example when using glut (glutDisplayFunc, glutKeyboardFunc, glutMouseFunc ...) when you only need a single instance of this class :
MyClass * ptr_global_instance = NULL;
extern "C" void mouse_buttons_callback(int button, int state, int x, int y) {
// c function call which calls your c++ class method
ptr_global_instance->mouse_buttons_cb(button, state, x, y);
}
void MyClass::mouse_buttons_cb(int button, int state, int x, int y) {
// this is actual body of callback - ie. if (button == GLUT_LEFT_BUTTON) ...
// implemented as a c++ method
}
void MyClass::setup_glut(int argc, char** argv) { // largely boilerplate glut setup
glutInit(&argc, argv);
// ... the usual suspects go here like glutInitWindowSize(900, 800); ...
setupMouseButtonCallback(); // <-- custom linkage of c++ to cb
// ... other glut setup calls here
}
void MyClass::setupMouseButtonCallback() {
// c++ method which registers c function callback
::ptr_global_instance = this;
::glutMouseFunc(::mouse_buttons_callback);
}
In your MyClass header we add :
void mouse_buttons_cb(int button, int state, int x, int y);
void setupMouseButtonCallback();
This also works using identical logic flows to setup your glut
call to glutDisplayFunc(display)