w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
pointers to functions / Function Tables
This line: #define DF(N) void N() { cout << "function " #N " called ... " << endl; } defines a new function with the name N. This works, because a macro simply creates a textual replacement so when the compiler sees it, it sees a perfectly valid function with the name N, as if you had typed the function void a() {... } and here there are the functions declared with the above macro, named a-g DF(a); DF(b); DF(c); DF(d); DF(e); DF(f); DF(g); Here: void (*func_table[])() = {a, b, c, d, e, f, g}; The above declared functions are simply assigned. The reason why you are subtracting the character is to get an index 0-n into the array of functions.

Categories : C++

Array of function pointers to member functions
The dot (member-of) operator is used for accessing members of an object. For classes and namespaces, you have to use the :: operator. Also, don't parenthesize, since & has lower precedence than :: and it's more readable like fptr[0] = &operate::add;

Categories : C++

Using delegates, anonymous(lambda) functions, and function pointers
Your question is still vague, but I'll put it like this. Cases: 1: Reusable and "static" If you reuse the SQL Statements and they are somewhat static, put them in Properties. And consider better names. 2: Reusable but "variable" though simple If you reuse the SQL Statements and they are variable but doesn't use much CPU, meaning they change by different states, and are very fast to create and build, then let them be as they are. 3: Reusable but "variable" and complex If you reuse the SQL Statements and they are variable but are very complex and requires alot of CPU power, put them in method, but call them as delegates, do not make them anonymous. 4: Not-Reusable but "variable" and complex If you will never reuse the SQL Statements(which probably not ever be the case) and they are var

Categories : C#

effective way perform custom function inside a delegate method on objC
Invoking a delegate method is no different than invoking any other method. Whatever thread invoked the method is the thread that method will run in. That being said, any sort of UI updating (you mentioned a label) must happen on the main thread or you will see some weird results. Edit: This is a common pattern when dealing with delegation between threads. - (void)main { // This is running some code on a background thread. dispatch_async(dispatch_get_main_queue(), ^{ // This is the main thread. Notify the delegate here. if ([delegate respondsToSelector:@selector(finishedDoingBackgroundWork)]) { [delegate finishedDoingBackgroundWork]; } }); }

Categories : IOS

c++ pointers to overloaded functions
Well the second attemp should work, if write is a pure function. From your code it seems you do have a memberfunction. Pointers to member-functions are ugly, you'd rather use a function object. However: you would have to post the whole code, it is not clear whether write is a member-function or not. Edit: if it is a member-function of FMS_logic::logical_file the syntax would be: void (FMS_logic::logical_file::*f)(const char *, const char *) = &FMS_logic::logical_file::write; This just applies for non-static member function, i.e. if a function is static or logical_file is just a namespace it is as you wrote it before.

Categories : C++

C - Pointers, functions and recursion
Within void BuildGraph(), BuildGraph(head->child, &G); should be BuildGraph(head->child, G);. No &, Likely the same with Push(head, &G); Within your build function, G is a Node **. Outside in main(), G is a Node *. Consider using a different and more expansive variable name than G within BuildGraph(). Maybe something like void BuildGraph(Node * head, Node ** AddressG) { if (head->child == NULL) { // No child printf("Head has no child! %d ", head->data); Push(head, AddressG); Print(AddressG, ">>"); return; } BuildGraph(head->child, AddressG); return; } I am confident that you compilation provided warning messages concerning this issue. If they did not recommend investigating how to turn them on.

Categories : C

Sending pointers to functions
pointers are values (often fitting in one word, or register, in your machine). It is a good habit to always initialize pointers (perhaps to NULL). A function like your allocate which takes some pointer and replaces immediately that pointer is losing the original pointer's value. BTW, you probably have a typedef struct somestruct_st structure; and I would prefer structure_t instead of structure as a type name. So basically, your function behaves like void allocate(structure *ptrold){ /// ptrold is never used in this function structure* ptr = malloc(sizeof(ptr)); } Unless you do something with your local ptr your function is leaking memory. You probably should return that ptr, or put it into some location (perhaps a memory field inside some structure or some global vari

Categories : C

Can I have a static array of pointers to functions in C++?
Should be made as simple as possible, but not simpler: typedef int (*t_MyFunc)(); t_MyFunc g_MyFuncArray[5]; And g_MyFuncArray can be static if you wish (but you should not if you want a global variable): static t_MyFunc g_MyFuncArray[5]; In a header file you should write: extern t_MyFunc g_MyFuncArray[5]; But don't forget to omit the static keyword in a .cpp file in this case.

Categories : C++

passing struct pointers to functions c++
Instead of loadFoo you can have constructor struct Foo{ float *bar; Foo( int size){ bar = new float[size]; //allocate memory //... Initialize bar } ~Foo() { delete bar;} }; OR using initializer_list #include <initializer_list> struct Foo{ float *bar; Foo( std::initializer_list<float> l){ bar = new float[l.size()]; //allocate memory std::initializer_list<float> ::iterator it = l.begin(); size_t i=0; for(;it!=l.end();++it,++i) bar[i] = *it; } ~Foo() { delete bar;} }; Also, make sure you follow rule of three

Categories : C++

Passing pointers between functions in an implementation of linked list
You are not returning anything from insertion() function when item is added to a list. So linked list may not get constructed properly. Probably, you should return start only when its added at the beginning, otherwise start in main() will not point to head of the list. sll_node* insertion(sll_node *start) { ... switch(choice) { case 0: return start; case 1: start = insert_begin(start); return start; //<----- return node break; case 2: start = insert_end(start); break; } ... }

Categories : C

C - Which is the advantage for the user of const in parameters of functions that are not pointers?
There is at least one reason why not to use const in non-pointer type parameters for external functions. With const your are exposing internals of the API which should be irrelevant for the API user. The use of const can generally helps for optimizations but its main usage is to prevent errors and document the API.

Categories : C

overloading functions with base class smart pointers
In principle this is the right way of doing it: Call the function on the base and polymorphism will do the right thing. However, your code won't compile: The func definitions in bar aren't valid (at least I'm not sure what you intended them for - what are they supposed to implement?) and the func call in callfunc dereferences the pointer twice. If you need concrete fixes, give the exact error.

Categories : C++

C - functions that return pointers, how to write efficient code?
A pointer is a really small thing. It's just a representation of the address of an object. You shouldn't be concerned about creating extra copies of a pointer (it's like creating an extra int). char* foo() { char* bar; // some stuff that mallocs a value and assigns to bar return bar; } char* x = foo(); In the simplified example above, the bar pointer is created on the stack, and the code in the comments points it at some memory in the heap (with a Malloc or something). When the function foo() is evaluated, the value of the pointer (e.g. The address of the memory) is popped off the stack and assigned to x. There is no unused pointer hanging around, it's just been reassigned. The memory that it points to remains exactly where it is and isn't duplicated. You aren't creating extra

Categories : C

std::transform with virtual call operator throws "global functions do not have 'this' pointers"
transform(v.begin(), v.end(), payVals.begin(), bind2nd(mem_fun(&PayOff::operator()),this)); The names in the call to transform must be looked up and resolved at the place where the call takes place. Which according to your comment is main. Inside main, you cannot use this. If you have a C++11 compiler you can opt to either use a lambda or std::bind: std::transform(std::begin(v), std::end(v), std::begin(payVals), [](PayOff* p) { (*p)(value); }); std::transform(std::begin(v), std::end(v), std::begin(payVals), std::bind(&Payoff::operator(), _1, value); // using std::placeholders::_1 In C++03 you can use boost::bind instead of std::bind or if that is not available you can create your own functor or adapter fu

Categories : C++

How can pointers to functions point to something that doesn't exist in memory yet? Why do prototypes have different addresses?
Functions are always in memory, but not on the stack. They are part of the code loaded with the rest of the program, and are put in a special read-only segment of memory. When you call the function, then space for its local variables (including arguments) are reserved on the stack.

Categories : C++

Accessing properties of a function inside different levels of its "prototype" functions -- and -- recursive functions
1. A) pass a variable to evenDeeper.Bar; B) use evenDeeper.bar.apply(new FooBar(args)) to access FooBar prototype using 'this'; C) assign evenDeeper.annoy the FooBar.annoy variable (not recommended because booleans are passed by value and it won't reflect changes to it) 2. A) use this.Bar() from within evenDeeper.Bar() and it should refer to itself unless you have changed the 'this' variable. B) pass this.Bar as a callback to this.Bar() and execute it within itself C) declare this.Bar() in a function context so it can refer to itself as simply Bar(), example follows: FooBar.prototype.evenDeeper = (function () { function Bar() { if (this.annoy) { alert('are you annoyed yet?'); } Bar.apply(this); } return { Bar: Bar, anotherOn

Categories : Javascript

Calling functions inside functions when the inner function's arguments will always be the same as the outer's
I honestly think your first technique is the best way to go and perfectly idiomatic. Still, here's another option: def outer_method(word) inner_lambda = lambda do puts "I really love " + word + "!" end inner_lambda.call puts word + " tastes like candy." end outer_method("onions") lambda creates a lexical closure, which means it captures the surrounding environment, including the reference to word.

Categories : Ruby

Function pointers - pass arguments to a function pointer
Fix typedef to typedef void (*VFUNCV)(int , double ); as fun1 and fun2 accepts two argument of type int and double

Categories : C

Static member array of pointers to member functions
If you have non static member functions with no arguments and returning bool you should write something like typedef bool (Hand::*hfunction_non_static)(); hfunction_non_static f_non_static [] = { &Hand::has_sflush, &Hand::has_poker, ....... }; Hand h; (h.*f_non_static[0])(); If you have static functions you should write something like typedef bool (*hfunction_static)(); hfunction_static f_static [] = {&Hand::has_sflush, ....}; f_static[0]();

Categories : C++

How do I use function pointers?
clientTree* (*pt2Function)(clientTree*, clientData) = NULL; Here you intialized pt2Function to NULL. And ptrFunction is a function pointer that can point to a function which can take 2 parameters of type clientTree*, clientData and whose return type is clientTree*. So, in your example you can use like - pt2Function = findClientDate; Now you can call the function findClientDate through pt2Function like - (*findClientDate)(t,u); So, in your example you should change the signature of the function clientTree*(*GetPtr2(int opCode))(clientTree*, clientData). It should be - clientTree* GetPtr2(int opCode); And now you can declare a function pointer like - clientTree* (*fPtr)(int opCode) = NULL; fPtr = GetPtr2;

Categories : C

Function Pointers in C++/CX
The second type in the ExpectException template (_RETURNTYPE in the declaration), needs to match the return type of the function passed into it. You've used int but your function returns void, so this gives a compiler error. If you want to be explicit here the second type should be void. However, as the compiler can figure out the type from the function parameter you don't need to specify it. Try this: Assert::ExpectException<InvalidArgumentException>(TestClass::TestMethod);

Categories : Misc

std::map with function pointers
The problem is that create() returns a type different than what is specified as the return type of the maps key template argument. Since everything uses A as the base / primary class type you should consider doing the same for create(). template <typename T> A* create(void) { return new T; } ^^^^

Categories : C++

Correct use of function pointers
Here's a complete program which uses your functions (all that you posted so far) exactly as they are. It works. The bug is in the part you aren't showing. #include <stdio.h> #include <string.h> #include <stdint.h> #include <stdlib.h> #include <assert.h> typedef uint8_t uint8; typedef uint16_t uint16; typedef uint32_t uint32; enum { QU_SUCCESS, QU_NO_MEMORY, QU_EMPTY }; typedef struct DL_LIST { uint16 tag; struct DL_LIST *previous; struct DL_LIST *next; void *object; uint32 size; } DL_LIST; DL_LIST *dl_extract(DL_LIST *node) { if (node != NULL) { if (node->previous != NULL) { node->previous->next = node->next; } if (node->next != NULL) { node->next

Categories : C

C - pointers as function arguments
The difference is simply said in the operations the processor will handle the code with. the value itself is just a adress in both cases, thats true. But as the address gets dereferenced, it's important for the processor and so also for the compiler, to know after dereferencing, what it will be handling with.

Categories : C

Puzzle + Function pointers
function is not a keyword in C++, Also function pointer declaration is wrong, it should be void general_function(bool (*choice)(string, char*)) { /**/ }

Categories : C++

Structure of pointers to function
Suppose you have pointer to function as you struct member like: struct newtype{ int a; char c; int (*f)(struct newtype*); } var; int fun(struct newtype* v){ return v->a; } You can call it as follows: int main(){ var.f=fun; var.f(&var); // ^.....^..... have to pass `var` as an argument to f() :( :( } //Comment: here in var.f(&var); I miss this pointer and C++, So for your case it should be just my_struct.my_pointer_to_a_function(value); Additionally points: Important to note in my example even you wants to access members of same structure variable you have to pass that. (its quite dissimilar than c++ object!) virtual functions in C++ classes. They are implemented in a similar fashion

Categories : C

Using pointers as function parameters
Assuming this worked (it doesn't compile, rightly so): total=x+y; it would give you the pointer that points at the address of x + the address of y. Since this is [nearly] always nonsense, the compiler doesn't allow you to add two pointers together. What you really want is to add the value that int *x and int *y POINTS AT, and store it in the place that total points at: *total = *x + *y;

Categories : C++

Pointers to function members
The error in GCC 4.8.1 is self-explanatory: error: must use ‘.’ or ‘->’ to call pointer-to-member function in ‘action (...)’, e.g. ‘(... ->* action) (...)’ basePointer->*action(); So, simply do that: (basePointer->*action)();

Categories : C++

Understanding function pointers
int* f2(){} A function that accepts nothing, and returns a pointer to an int. int (*p)(); A pointer to: A function that accepts nothing and returns an int You have a type mismatch. p is not a pointer to the type of f2 If you have trouble understanding such definitions, like all mortal do, use the spiral rule of thumb

Categories : C++

There is a type for function pointers in C++?
If you're asking for pointers-to-member-functions, these exist as part of the core language, though I wouldn't call them "simple": #include <iostream> struct T { T(int x) : x(x) {}; void foo() { std::cout << x; } private: int x; }; int main() { typedef void (T::*P)(); P fooptr = &T::foo; T obj(5); (obj.*fooptr)(); // Output: 5 } (live demo) std::function, when combined with std::bind, is a somewhat nicer alternative: #include <iostream> #include <functional> struct T { T(int x) : x(x) {}; void foo() { std::cout << x; } private: int x; }; int main() { using namespace std::placeholders; // for _1, _2, _3... std::function<void()> f = std::bind(&T::foo, _1); // or auto f = ... T obj(5); f(o

Categories : C++

VC++ Function Pointers in Class
Function pointer syntax goes as follows returnType (*yourFuncName)(argumentTypes); so you'll need to redefine your member to something like this Point3 (*getPointFunc)(void);

Categories : C++

function pointers between classes
CTop::func1 is a member function. &CTop::func1 is NOT a function pointer, it is a pointer to member (function). Those can not be mixed either in storing or calling. it is not compatible with int (*fn)(void), as the latter takes no arguments and the former requires an object that is passed as the hidden this. For these reasons you can't have a simple but uniform facility. You either can go with simple function pointers, or pairs of PTM+object pointer, or use wrappers -- handmade or stock like boost::function fueled by boost::bind. If you have C++11 or TR1 you can use the std:: equivalents of the latter.

Categories : C++

Does "this" also adapt to function pointers?
You need to specify the function name explicitly: void DoesSomething(){ this->DoesSomething(default1, default2); } void DoesSomething(int myValue1){ this->DoesSomething(myValue1, default2); } void DoesSomething(int myValue1, int myValue2){ //Do stuff } There is no implicit knowledge of the other function with a given name by context, like you're describing. Note that in Java, this only works for constructors, and is called Constructor Chaining. It does not handle this for methods in general. C++11 also adds support for this same concept (as delegating constructors), though the syntax is different than Java, C#, and other languages with this concept. For constructors, in C++11, you can write: SomeType() : SomeType(42) {} SomeType(int arg) { // ...

Categories : C++

How to use function pointers in different classes?
Do not use function pointers in the first place when using C++. There is an easier and more elagant solution - an interface. i.e. class Interface { public: virtual int CallMe() = 0; }; class B : public Interface { int CallMe() { return 5; }; class A : public Interface { private: Interface *m_i = 0; public: A(Interface *i) : m_i(i) { } A() : m_i(this) { }; void DoIt() { cout << m_i->CallMe() << endl; } int CallMe() { return 8; } }; int main() { A a(new B); // Coult be any object that implements Interface (as yes it is a memory leak A aa(); a.DoIt(); // Will print 5 aa.DoIt(); // WIll print 8 return 0; }

Categories : C++

C++ template design with function pointers
Try something like this. #include <iostream> using namespace std; typedef void (*cb1)(void); typedef int (*cb2)(int, int); typedef char (*cb3)(int, int, char); template <class CallbackType> class CSubscriber { public: CSubscriber(): fcn1(0), fcn2(0), fcn3(0) {}; virtual ~CSubscriber(){}; CSubscriber(cb1 fcn): fcn1(fcn), fcn2(0), fcn3(0), a(), b() {}; CSubscriber(cb2 fcn, int p1, int p2): fcn1(0), fcn2(fcn), fcn3(0), a(p1), b(p2) {}; int execute_cb() { if ( fcn1 != 0 ) { (*fcn1)(); } if ( fcn2 != 0 ) { (*fcn2)(a,b); } }; protected: cb1 fcn1; cb2 fcn2; cb3 fcn3; int a, b; }; void fcn1() { cout << "in fcn1" << endl; }; int fcn2(int a, int b) { cout <

Categories : C++

Pointers to a class within void function
You pass units into the function by value. This means that the units pointer within the function starts out as a copy of the one in the calling code. Within the function you assign a new value to the local units variable (i.e. the address of some newly created objects). Then when the function terminates, the local variable passes out of scope and the objects it pointed to are lost. The pointer in the calling code is never modified, and knows nothing about any of this. Pass it by reference instead: void initialize(grid *grids, unit ** &units)

Categories : C++

C++ programming riddle, fun with function pointers
A function pointer will be converted to bool when using with cout. Why the function pointer is not converted to a void * implicitly, which is what operator << overloads on? because function pointers are not object pointers. C++11 §4.10/2: A prvalue of type “pointer to cv T,” where T is an object type, can be converted to a prvalue of type “pointer to cv void”. The result of converting a “pointer to cv T” to a “pointer to cv void” points to the start of the storage location where the object of type T resides, as if the object is a most derived object (1.8) of type T (that is, not a base class subobject). The null pointer value is converted to the null pointer value of the destination type.

Categories : C++

Member function pointers for subclass
A pointer to member of derived is not convertible to a pointer to member of base. If it were, you could do things like (baseInstance.*methodOfDerived)() which doesn't make sense. The covariance goes the other way round: you could take a pointer to member of base, and call it on an instance of derived. It's not quite clear what you are trying to achieve, but your current approach ain't going to fly. You need to reconsider your design.

Categories : C++

Using a pointer to function pointers without typedef?
The real answer is given in one of the comments: double *(**fns)(double *, double) would declare a pointer to pointer to function returning a double *, with the arguments a double * and a double. However, it's quite hard to read even before it became a pointer to pointer, so I'm not convinced you'd want to do this just to save a little bit of typing... (typedef and a name). Of course, since this is C++, using std::vector<std::function<double *(double *, double)>> fns; would be the "right" thing to do, or perhaps even std::vector<std::function<std::vector<double>(std::vector<double>, double)>> fns;`

Categories : C++

Retrieving function pointers from container
std::queue::pop() returns void. You need a call to std::queue::front(), followed by one to std::queue::pop(). I would suggest using a typedef for the function pointer, for the sake of readability.

Categories : C++



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.