I am doing Box2D programming, and heads up, I am a total noob to C++ and C. I am an Objective-C guy, and that is why it is becoming really hard for me to understand the language. Especially:
->
Basically I understand that this is used for referencing different methods or functions or variables/properties like below:
body->GetWorld()->DestroyBody(body);
So is this equivalent to dot notation in Objective-C:
// made up example
[body.world destroyBody];
or
[self destroyBody:body.world];
Or something similar? I really don't understand this. Can someone give me a heads up on what this is. Thanks!
I don't know Objective-C, but I can explain difference between -> and . in C and C++, hope that helps.
. is operator that allows you to access member of struct/class instance. a->b is the same as (*a).b - so it first dereferences the pointer, then accesses member of instance that the pointer was pointing to.
Also, there is a case that Luchian has mentioned - overloading of operator->() of given class. In case when class you are using does overload this operator, the behavior will be different, defined by the class - it can return virtually everything it wants.
I don't know much about Objective-C, but I can try to give you some help about C++: assuming that you define a class Foo in C++, with a method bar():
class Foo
{
public:
void bar();
...
};
If you allocate an instance of Foo on the stack, you use dot notation (.) to call the method bar():
Foo f;
f.bar();
If you have a pointer to an instance of Foo, you use the arrow notation (->) to call the method bar():
Foo* pf; // must point to some instance of Foo
pf->bar();
(To complicate things, there are also references, which have value syntax and pointer semantics: if you have a reference to Foo (e.g. Foo& f) you still use dot notation: f.bar();.)
. is used to access object members, -> is used to access members through a pointer. Usually. operator -> can be overloaded, meaning you can also use it on objects:
struct X
{
X* other;
X* operator->() {return other;}
};
X x;
x->other;
In this case, x->other doesn't reffer to x.other, but to x.other.other. :D
No, using . to access Objective-C properties is not the same as either -> or . to access struct and class members in C and C++.
The Objective-C property accessor works on values of type id (which is a pointer type), but uses special naming conventions to decide what it actually does. It can directly access a property data member, making it similar to -> for data member access. Or it can look up special functions for getting and/or setting the property value, in which case it's syntax sugar for a message send.
Except in the case of operator overloading in C++, -> is always the same as dereferencing a pointer and then accessing the member referred to. a->b is equivalent to (*a).b. b may be a data member for a member function, but the accessed member will have the exact name referred to in b, not some mutation of it based on any special naming convention. If b names a member function then it may be a virtual function, which has some similarities to, but is not the same as, message sends in Objective-C. b may also be an overloaded member function in C++ which has no equivalent in Objective-C.
The addition of the . syntax for accessing object properties in Objective-C violates Objective-C's design principal that new features should look new. Using #, the [] message sending syntax, and the special keywords to define Objective-C objects are examples where Objective-C previously followed this design principal.
This is objective-c code.
#interface Foo : NSObject
{
NSInteger _a;
}
#property (nonatomaic, assign) NSInteger a;
#end
#implement Foo
#synthesize a = _a;
#end
You know '#synthesize' phrase.
#synthesize create bellow codes.
- (NSInteger)a
{
return _a;
}
- (void)setA:(NSInteger)aa
{
return _a = aa;
}
Let's access property a.
void main()
{
Foo foo = [[Foo alloc] init];
foo.a = 1;
}
Must assigned foo.a as 1.
But compiler call as bellow.
void main()
{
Foo foo = [[Foo alloc] init];
[foo setA:1];
}
foo.a = 1 and [foo setA:1] is same.
foo.a = 1 calls [foo setA:1].
Bellow, Written in C.
class Foo
{
private:
int _a;
public:
int getA();
void setA(const int aa);
};
int Foo::getA()
{
return _a;
}
void Foo::setA(const int aa)
{
_a = aa;
}
// local allocation example.
void main()
{
Foo foo;
foo.setA(1);
}
// Heap allocation example.
void main()
{
Foo *foo = new Foo();
foo->setA(1);
delete foo;
}
// Pointer (like object objectve-c).
void main()
{
Foo foo1;
foo1.setA(1);
Foo *foo2 = &foo1;
foo2->setA(2);
printf("result>>> %d, %d", foo1.a, foo2->a);
}
result>>> 2, 2
foo1.a and foo2->a is 2 also.
Objectve-C example bellow.
void main()
{
Foo *foo1 = [[Foo alloc] init];
foo1.a = 1;
Foo *foo2 = foo1;
foo2.a = 2;
NSLog(#"result>>> %d, %d", foo1.a, foo2.a);
}
result>>> 2, 2
Have a good day.
Thank you.
Related
I have a class Ghost that has an array of functions. This class Ghost is an
array too. How do I call the functions in main? I cant find a way to call this functions. I have seen some examples but nothing like this.
class Ghost;
typedef void(Ghost::* Func)();
class Ghost
{
public:
Func func;
public:
void init() {};
void running_random() {};
void running_afraid() {};
void dead() {};
Ghost(){
func = new Func[5];
func[0] = &Ghost::init;
func[1] = &Ghost::random;
func[2] = &Ghost::running_afraid;
func[4] = &Ghost::dead;
}
};
int main()
{
Ghost ph[4];
ph[0]->*func[0](); //???
ph[0]->(*func[0]()); //???
(ph[0]->*func[0])(); //???
}
"I have a class Ghost that has an array of functions"
That isn't accurate. Those aren't just functions; they're pointers to member functions, which are distinct beasts unto their own.
Of the things wrong in this code.
Func func should be Func *func;
The way you had it, Func func; declares a single pointer-to-member variable, and you clearly want an array of them.
Wrong member-access operator.
You're using operator ->*, which should be used against a pointer to object married to a pointer to member. But you don't have a pointer to object. Given Ghost ph[4]; that means ph[0] is not Ghost*, it's Ghost. Therefore, operator .* should be used.
Improper access to func member.
The array holding the pointers to members is a member of Ghost. Using the member access operators (operator .* or operator ->*) doesn't magically grant access to member func. That's just where you chose to store those member function pointers. Those operators don't behave like operator . and operator ->
Incorrect object and member coupling.
When coupling a pointer-to-member with a concrete object using operator .* (or a pointer to object using operator ->*), the full expression of the coupling should be enclosed in parentheses, then the argument list should follow in its own parentheses. In short, only the last of these makes sense (but is still broken due to the plethora of problems above).
ph[0]->*func[0]();
ph[0]->(*func[0]());
(ph[0]->*func[0])(); // closest to correct
Summary
After all of that, we can craft something that will actually work:
#include <iostream>
class Ghost;
typedef void(Ghost::*Func)();
class Ghost
{
public:
Func* func;
public:
void init() {std::cout << "here!!\n"; };
void running_random() {};
void running_afraid() {};
void dead() {};
Ghost(){
func = new Func[5];
func[0] = &Ghost::init;
func[1] = &Ghost::running_random;
func[2] = &Ghost::running_afraid;
func[4] = &Ghost::dead;
}
};
int main()
{
Ghost ph[4];
(ph[0].*ph[0].func[0])();
}
Output
here!!
I leave the ensuing memory leaks and realization this is probably not the architecture you really wanted in the first place for you to handle. But those were the problem, and a resolution, to the code you posted.
I need the syntax for a lambda expression that will return a pointer to a member function.
For example I have class A:
class A
{
int x;
void (A::*SomeFunction)();
}
I want to set SomeFunction to a lambda. I tried doing it like this:
A a();
a.SomeFunction = [this](){ printf("Hello from lambada %d",this->x);};
The problem is that:
[this](){ printf("Hello from lambda %d",this->x);};
does not give me a pointer to a member function of class A. it gives me a pointer to a normal function. How do i declare inside the lambda that this is a member function of A.
Alternativly if such a thing isn't possible in cpp. How do you suggest I'll access variable x of class A from the function that SomeFunction is pointing at without using virtual functions (this kind of code will run about 700 times per second).
Edit:
To make it clear I do care about performance. but the main reason why I need this is specific design problems not performance.
I understand this is probably not possible to do in cpp.
Workarounds suggestions would be welcomed.
That is not possible for several reasons.
First, a pointer to member function is different in type from a pointer to stand-alone function, and non-capturing lambdas can only be converted to pointers to standalone functions.
Second, your lambda is capturing, and as such, it can not be converted to a pointer to function at all, and can only remain a functor of unspecified type.
However, you shouldn't think too much into it and just store a lambda in a std::function. Granted, you will end with virtual dispatch and some performance degradation associated with that, but 700 times a second is nothing, and you will never detect a hit because of virtual dispatch.
It's impossible to add extra methods to a class after its definition. Therefore, since there are no methods in your class A, it's impossible to ever set A::SomeFunction to point to any non-static method of A. As a workaround, you could have
void (*SomeFunction)(A*);
and
A a {}; // note {} instead of ()
a.SomeFunction = [](A* a){ /* do something with a->x */ };
From the comments:
This is part of an ECS implemention. and I am simply not willing to create a new class for etch system i want to give the user the option to declare the system in the scene constructor or inheriate from the system class.
You want different behavior from the same class without any indirection? You'll have to give up one.
But you don't have to write a class for each system either. You can make the class a template, so the compiler can generate a class for each systems:
template<typename T>
struct A : private T {
A(T function) noexcept : T{std::move(function)} {}
void SomeFunction() {
(*this)(this);
}
int x = 0;
};
It can then be used like that:
auto lambda = [](auto a){ printf("Hello from lambda %d",a->x); };
auto my_a = A{lambda}; // Generate a new A type from lambda
my_a.SomeFunction(); // calls the lambda!
Well following up for future people here's a workaround to make it look a bit nicer.
I created a template class
template <class Parent,class Return, class...Params>
struct MemberLambda
{
Parent* self; // pointer to self
void (*lambda)(Parent * self,Params...);//the lambda
MemberLambda() = default;//Constructor
MemberLambda(Parent* self, void(*lambda)(Parent* self,Params...)) :
self(self),lambda(lambda) {};//Constructor
Return operator()(Params... p) const { return lambda(self,p...); };
void operator=(void (*lambda)(Parent* self, Params...)) {
this->lambda = lambda;
}
};
Usage in class:
class A {
public:
int someMember;
MemberLambda<A, void, int, int> func =
MemberLambda<A, void, int, int>(this, nullptr);
};
*Note in the example I set the lambda to nullptr but it can be set to a lambda expression.
In the example, the lambda is a member of A takes two ints and returns void.
User usage:
A a;
a.someMember = 3;
a.func = [](A* self, int a, int b){ std::cout << self->someMember + a + b; };
a.func(5,6);
Will output 14, which is 3 + 5 + 6.
How do I obtain a function pointer for a class member function, and later call that member function with a specific object? I’d like to write:
class Dog : Animal
{
Dog ();
void bark ();
}
…
Dog* pDog = new Dog ();
BarkFunction pBark = &Dog::bark;
(*pBark) (pDog);
…
Also, if possible, I’d like to invoke the constructor via a pointer as well:
NewAnimalFunction pNew = &Dog::Dog;
Animal* pAnimal = (*pNew)();
Is this possible, and if so, what is the preferred way to do this?
Read this for detail :
// 1 define a function pointer and initialize to NULL
int (TMyClass::*pt2ConstMember)(float, char, char) const = NULL;
// C++
class TMyClass
{
public:
int DoIt(float a, char b, char c){ cout << "TMyClass::DoIt"<< endl; return a+b+c;};
int DoMore(float a, char b, char c) const
{ cout << "TMyClass::DoMore" << endl; return a-b+c; };
/* more of TMyClass */
};
pt2ConstMember = &TMyClass::DoIt; // note: <pt2Member> may also legally point to &DoMore
// Calling Function using Function Pointer
(*this.*pt2ConstMember)(12, 'a', 'b');
How do I obtain a function pointer for a class member function, and later call that member function with a specific object?
It's easiest to start with a typedef. For a member function, you add the classname in the type declaration:
typedef void(Dog::*BarkFunction)(void);
Then to invoke the method, you use the ->* operator:
(pDog->*pBark)();
Also, if possible, I’d like to invoke the constructor via a pointer as well. Is this possible, and if so, what is the preferred way to do this?
I don't believe you can work with constructors like this - ctors and dtors are special. The normal way to achieve that sort of thing would be using a factory method, which is basically just a static function that calls the constructor for you. See the code below for an example.
I have modified your code to do basically what you describe. There's some caveats below.
#include <iostream>
class Animal
{
public:
typedef Animal*(*NewAnimalFunction)(void);
virtual void makeNoise()
{
std::cout << "M00f!" << std::endl;
}
};
class Dog : public Animal
{
public:
typedef void(Dog::*BarkFunction)(void);
typedef Dog*(*NewDogFunction)(void);
Dog () {}
static Dog* newDog()
{
return new Dog;
}
virtual void makeNoise ()
{
std::cout << "Woof!" << std::endl;
}
};
int main(int argc, char* argv[])
{
// Call member function via method pointer
Dog* pDog = new Dog ();
Dog::BarkFunction pBark = &Dog::makeNoise;
(pDog->*pBark)();
// Construct instance via factory method
Dog::NewDogFunction pNew = &Dog::newDog;
Animal* pAnimal = (*pNew)();
pAnimal->makeNoise();
return 0;
}
Now although you can normally use a Dog* in the place of an Animal* thanks to the magic of polymorphism, the type of a function pointer does not follow the lookup rules of class hierarchy. So an Animal method pointer is not compatible with a Dog method pointer, in other words you can't assign a Dog* (*)() to a variable of type Animal* (*)().
The static newDog method is a simple example of a factory, which simply creates and returns new instances. Being a static function, it has a regular typedef (with no class qualifier).
Having answered the above, I do wonder if there's not a better way of achieving what you need. There's a few specific scenarios where you would do this sort of thing, but you might find there's other patterns that work better for your problem. If you describe in more general terms what you are trying to achieve, the hive-mind may prove even more useful!
Related to the above, you will no doubt find the Boost bind library and other related modules very useful.
I don't think anyone has explained here that one issue is that you need "member pointers" rather than normal function pointers.
Member pointers to functions are not simply function pointers. In implementation terms, the compiler cannot use a simple function address because, in general, you don't know the address to call until you know which object to dereference for (think virtual functions). You also need to know the object in order to provide the this implicit parameter, of course.
Having said that you need them, now I'll say that you really need to avoid them. Seriously, member pointers are a pain. It is much more sane to look at object-oriented design patterns that achieve the same goal, or to use a boost::function or whatever as mentioned above - assuming you get to make that choice, that is.
If you are supplying that function pointer to existing code, so you really need a simple function pointer, you should write a function as a static member of the class. A static member function doesn't understand this, so you'll need to pass the object in as an explicit parameter. There was once a not-that-unusual idiom along these lines for working with old C code that needs function pointers
class myclass
{
public:
virtual void myrealmethod () = 0;
static void myfunction (myclass *p);
}
void myclass::myfunction (myclass *p)
{
p->myrealmethod ();
}
Since myfunction is really just a normal function (scope issues aside), a function pointer can be found in the normal C way.
EDIT - this kind of method is called a "class method" or a "static member function". The main difference from a non-member function is that, if you reference it from outside the class, you must specify the scope using the :: scope resolution operator. For example, to get the function pointer, use &myclass::myfunction and to call it use myclass::myfunction (arg);.
This kind of thing is fairly common when using the old Win32 APIs, which were originally designed for C rather than C++. Of course in that case, the parameter is normally LPARAM or similar rather than a pointer, and some casting is needed.
typedef void (Dog::*memfun)();
memfun doSomething = &Dog::bark;
....
(pDog->*doSomething)(); // if pDog is a pointer
// (pDog.*doSomething)(); // if pDog is a reference
Minimal runnable example
main.cpp
#include <cassert>
class C {
public:
int i;
C(int i) : i(i) {}
int m(int j) { return this->i + j; }
};
int main() {
// Get a method pointer.
int (C::*p)(int) = &C::m;
// Create a test object.
C c(1);
C *cp = &c;
// Operator .*
assert((c.*p)(2) == 3);
// Operator ->*
assert((cp->*p)(2) == 3);
}
Compile and run:
g++ -ggdb3 -O0 -std=c++11 -Wall -Wextra -pedantic -o main.out main.cpp
./main.out
Tested in Ubuntu 18.04.
You cannot change the order of the parenthesis or omit them. The following do not work:
c.*p(2)
c.*(p)(2)
GCC 9.2 would fail with:
main.cpp: In function ‘int main()’:
main.cpp:19:18: error: must use ‘.*’ or ‘->*’ to call pointer-to-member function in ‘p (...)’, e.g. ‘(... ->* p) (...)’
19 | assert(c.*p(2) == 3);
|
C++11 standard
.* and ->* are a single operators introduced in C++ for this purpose, and not present in C.
C++11 N3337 standard draft:
2.13 "Operators and punctuators" has a list of all operators, which contains .* and ->*.
5.5 "Pointer-to-member operators" explains what they do
I came here to learn how to create a function pointer (not a method pointer) from a method but none of the answers here provide a solution. Here is what I came up with:
template <class T> struct MethodHelper;
template <class C, class Ret, class... Args> struct MethodHelper<Ret (C::*)(Args...)> {
using T = Ret (C::*)(Args...);
template <T m> static Ret call(C* object, Args... args) {
return (object->*m)(args...);
}
};
#define METHOD_FP(m) MethodHelper<decltype(m)>::call<m>
So for your example you would now do:
Dog dog;
using BarkFunction = void (*)(Dog*);
BarkFunction bark = METHOD_FP(&Dog::bark);
(*bark)(&dog); // or simply bark(&dog)
Edit:
Using C++17, there is an even better solution:
template <auto m> struct MethodHelper;
template <class C, class Ret, class... Args, Ret (C::*m)(Args...)> struct MethodHelper<m> {
static Ret call(C* object, Args... args) {
return (object->*m)(args...);
}
};
which can be used directly without the macro:
Dog dog;
using BarkFunction = void (*)(Dog*);
BarkFunction bark = MethodHelper<&Dog::bark>::call;
(*bark)(&dog); // or simply bark(&dog)
For methods with modifiers like const you might need some more specializations like:
template <class C, class Ret, class... Args, Ret (C::*m)(Args...) const> struct MethodHelper<m> {
static Ret call(const C* object, Args... args) {
return (object->*m)(args...);
}
};
A function pointer to a class member is a problem that is really suited to using boost::function. Small example:
#include <boost/function.hpp>
#include <iostream>
class Dog
{
public:
Dog (int i) : tmp(i) {}
void bark ()
{
std::cout << "woof: " << tmp << std::endl;
}
private:
int tmp;
};
int main()
{
Dog* pDog1 = new Dog (1);
Dog* pDog2 = new Dog (2);
//BarkFunction pBark = &Dog::bark;
boost::function<void (Dog*)> f1 = &Dog::bark;
f1(pDog1);
f1(pDog2);
}
Reason why you cannot use function pointers to call member functions is that
ordinary function pointers are usually just the memory address of the function.
To call a member function, you need to know two things:
Which member function to call
Which instance should be used (whose member function)
Ordinary function pointers cannot store both. C++ member function pointers are used
to store a), which is why you need to specify the instance explicitly when calling a member function pointer.
To create a new object you can either use placement new, as mentioned above, or have your class implement a clone() method that creates a copy of the object. You can then call this clone method using a member function pointer as explained above to create new instances of the object. The advantage of clone is that sometimes you may be working with a pointer to a base class where you don't know the type of the object. In this case a clone() method can be easier to use. Also, clone() will let you copy the state of the object if that is what you want.
I did this with std::function and std::bind..
I wrote this EventManager class that stores a vector of handlers in an unordered_map that maps event types (which are just const unsigned int, I have a big namespace-scoped enum of them) to a vector of handlers for that event type.
In my EventManagerTests class, I set up an event handler, like this:
auto delegate = std::bind(&EventManagerTests::OnKeyDown, this, std::placeholders::_1);
event_manager.AddEventListener(kEventKeyDown, delegate);
Here's the AddEventListener function:
std::vector<EventHandler>::iterator EventManager::AddEventListener(EventType _event_type, EventHandler _handler)
{
if (listeners_.count(_event_type) == 0)
{
listeners_.emplace(_event_type, new std::vector<EventHandler>());
}
std::vector<EventHandler>::iterator it = listeners_[_event_type]->end();
listeners_[_event_type]->push_back(_handler);
return it;
}
Here's the EventHandler type definition:
typedef std::function<void(Event *)> EventHandler;
Then back in EventManagerTests::RaiseEvent, I do this:
Engine::KeyDownEvent event(39);
event_manager.RaiseEvent(1, (Engine::Event*) & event);
Here's the code for EventManager::RaiseEvent:
void EventManager::RaiseEvent(EventType _event_type, Event * _event)
{
if (listeners_.count(_event_type) > 0)
{
std::vector<EventHandler> * vec = listeners_[_event_type];
std::for_each(
begin(*vec),
end(*vec),
[_event](EventHandler handler) mutable
{
(handler)(_event);
}
);
}
}
This works. I get the call in EventManagerTests::OnKeyDown. I have to delete the vectors come clean up time, but once I do that there are no leaks. Raising an event takes about 5 microseconds on my computer, which is circa 2008. Not exactly super fast, but. Fair enough as long as I know that and I don't use it in ultra hot code.
I'd like to speed it up by rolling my own std::function and std::bind, and maybe using an array of arrays rather than an unordered_map of vectors, but I haven't quite figured out how to store a member function pointer and call it from code that knows nothing about the class being called. Eyelash's answer looks Very Interesting..
This question already has answers here:
When do I use a dot, arrow, or double colon to refer to members of a class in C++?
(4 answers)
Closed 8 years ago.
Apologies for a question that I assume is extremely basic.
I am having trouble finding out online the difference between the operator :: and . in C++
I have a few years experience with C# and Java, and am familiar with the concept of using . operator for member access.
Could anyone explain when these would be used and what the difference is?
Thanks for your time
The difference is the first is the scope resolution operator and the second is a member access syntax.
So, :: (scope resolution) can be used to access something further in a namespace like a nested class, or to access a static function. The . period operator will simply access any visible member of the class instance you're using it on.
Some examples:
class A {
public:
class B { };
static void foo() {}
void bar() {}
};
//Create instance of nested class B.
A::B myB;
//Call normal function on instance of A.
A a;
a.bar();
//Call the static function on the class (rather than on an instance of the class).
A::foo();
Note that a static function or data member is one that belongs to the class itself, whether or not you have created any instances of that class. So, if I had a static variable in my class, and crated a thousand instances of that class, there's only 1 instance of that static variable still. There would be 1000 instances of any other member that wasn't static though, one per instance of the class.
One more interesting option for when you come to it :) You'll also see:
//Create a pointer to a dynamically allocated A.
A* a = new A();
//Invoke/call bar through the pointer.
a->bar();
//Free the memory!!!
delete a;
Dynamic memory can be a little more confusing if you haven't learned it yet, so I won't go into details. Just wanted you to know that you can access members with { :: or . or -> } :)
in C++ :: is the scope resolution operator. It is used to distinguish namespaces, and static methods, basically any case you don't have an object. Where . is used to access things inside an object.
C# uses the . operator for both of them.
namespace Foo
{
public class Bar
{
public void Method()
{
}
public static void Instance()
{
}
}
}
in C# you would write code like this:
var blah = new Foo.Bar();
blah.Method();
but the equivalent C++ code would look more like this:
Foo::Bar blah;
blah.Method();
But note that the static method would also be accessed using the scope resolution operator, because you're not referencing an object.
Foo::Bar::Instance();
Where again, the C# code would only use the dot operator
Foo.Bar.Instance();
:: is for namespaces and static member access. C# uses the dot-operator for namespaces instead.
. is for non-static member access.
Not an exhaustive delineation, but it's the relevant bits that may confuse you in light of C# and Java.
For further information, see
IBM - Scope Resolution Operator
IBM - Dot Operator
:: is the scope resolution operator, so when you are resolving a scope, such as a namespace or class, you use that. For member access, you have .
The scope operator :: may be hard to understand if you don't understand namespaces or classes. A namespace is like a container for the names of various things in your code. They're generally used to disambiguate names that are common across libraries. Say both namespaces std and example have the function foobar(). So the compiler knows which function you want to use, you prepend it as either std::foobar() or example::foobar().
The :: operator can also be used when telling the compiler you want to define a function declared in a class or structure. For instance:
class foobar()
{
public:
void hello();
int number; //assume there is a constructor that sets this to 5
}
void foobar::hello()
{
cout << "Hello, world!" << endl;
}
The . operator is used when you wish to use a member of a class or structure. For instance:
foobar foo;
foo.hello();
cout << foo.number << endl;
Assuming the class is completed by writing a constructor, the output of this would be expected to be:
Hello, world!
5
You use the . operator the same in java, when accessing members of a class once its created in the program.
the :: is used in number of cases:
When you define a method in the .h/.cpp of a certain class, write
class::methodName()
either for prototyping it, or implementing it.
Also, if you don't explicitly state what namespace you use, you'd have to to use it
std::cout << "This is the output";
instead of just using cout << "This is the output;
Maybe there are more, but i don't remember right now, my C++ is a bit rusty.
In C++, :: is for identifying scope. This can mean namespace scope or class scope.
Eg.
int x;
namespace N {
int x;
struct foo {
static double x;
double y;
};
struct bar: public foo {
double y;
};
}
int main()
{
int x; // we have a local, hiding the global name
x = ::x; // explicitly identify the x in global scope
x += N::x; // explicitly identify the x in namespace N
N::foo::x = x; // set the static member of foo to our local integer
N::foo f;
f.y = f.x; // the static member is implicitly scoped by the object
f.y += N::foo::x; // or explicitly scoped
N::bar b;
assert(b.x == N::foo::x); // this static member is inherited
b.y = b.x; // we get N::bar::y by default
b.N::foo::y = b.y; // explicitly request the hidden inherited one
}
// we need to define the storage for that static somewhere too ...
int N::foo::x (0.0);
I have a std::map which I'm trying to store void pointers for the values. The problem is, most of the pointer I'm trying to store are methods in a class and have different amount of params. I know for the params I can use a va list so thats not too much of a problem, the problem would be the actual pointer itself.
This is what I have:
class A
{
public:
A();
void methodA(...);
};
class B
{
public:
B();
void methodB(...);
};
void method_no_class(...) { }
std::map<int, void(*)(...)> my_map;
my_map[0] = &method_no_class;
B* cb = new B();
my_map[1] = &cb->methodB; // will return error
Maybe this information my help you:
http://www.parashift.com/c++-faq-lite/pointers-to-members.html#faq-33.1
Pointer to method is of different type than pointer to function. If you want to store them both in single collection you have to do manual casts.
The clean OO way would be to define a command interface. The interface would take an instance (of A or B) and all parameters. In the invoke() method, it would call the method of the instance.
You could then use a map of these command interfaces (just define a common subclass for them which defines the abstract invoke() method). The compiler would check all types and arguments for you, and you wouldn't have to use varargs.
Following up on Kamil Szot's answer, the C++ FAQ (and the book) is an excellent reference to the murky depths of C++ and object oriented programming in general. Section 33 addresses specifically the problem you are having:
In C++, member functions have an implicit parameter which points to the object (the this pointer inside the member function). Normal C functions can be thought of as having a different calling convention from member functions, so the types of their pointers (pointer-to-member-function vs. pointer-to-function) are different and incompatible.
Of course, the answer to your question is somewhat lacking in details.
You might want to look at method operaters ->, ::, and their friends. I'll try to find a better link but start here.
UPDATE: hopefully this is a better article for method pointers and operators.
You should functionoids here. They can be used as a flexible and type safe replacement for function pointers with different signatures. A abstract base class is needed. It contains the actual function invocation with the common parameters, if there are any.
class Functioniod: public YourClass {
virtual void execute(char d, common_parameters,...) = 0
}
For every function you want to use, you create a derived class. The constructor contains the function-specific parameters, and the execute() function the actual call. This execute function is later called instead of the function pointer. It needs to have the same signature in every functionoid. It could call something different in any other class too, of course.
class FuncA: public Functionoid {
FuncA(int _a, float _b, string _c, function-specific-parameters...) {
a = _a; b = _b; c = _c;
}
void execute(char d, common-parameters,...) {
call-to-member(d, a, b, c);
}
int a;
float b;
string c;
}
Now if you want to use this as a replacement for your member function pointer, you would do:
std::map<int, *Functionoid> my_map;
my_map[0] = new FuncA(someInt, someFloat, someString);
my_map[1] = new FuncB(some-other-parameters...);
and execute them with
my_map[0]->execute(common-parm);
my_map[1]->execute(common-parm);
Here's an example code to get you started. Haven't compiled it, so might require some tuning.
#define func(Instance,Method,Class) \
(__int64(Instance)<<32 + __int64(&Class::Method))
#define invoke(Func,Method,Class) \
invoke1(Func,(Class*)0)->*invoke2(Func,&Class::Method)
template<class Class>
Class* invoke1(__int64 Func,Class*)
{
return (Class*)(int)(Func>>32);
}
template<class Method>
Method invoke2(__int64 Func,Method)
{
return (Method)(int)Func;
}
------------ USAGE ------------
class B
{
void methodB(int a,float b){}
};
std::map<int, __int64> my_map;
my_map[0] = func(cb,methodB,B);
invoke(my_map[0],methodB,B)(1,2.f);