Below code doesn't compile, please help me where I'm missing. I have member functions with different return types and I need to call those functions by just passing a string name. So I have created a map, Below is the example which matches my requirement, but I'm not able to compile.
template<typename T1>
shared_ptr<T1> GetBasicClassInfo()
{
T1 obj;
shared_ptr<T1> pobj( new T1);
return pobj;
}
class BasicClass
{
public:
std::string GetValue()
{
return "Successfull";
}
int GetInt()
{
return 5;
}
};
template<typename T>
std::map<std::string, std::function<T()>> GetPropertyValue ={
{"int",&GetBasicClassInfo<BasicClass>()->GetInt},
{"string",&GetBasicClassInfo<BasicClass>()->GetValue}
};
int main()
{
cout<<GetPropertyValue["int"]()<<endl;
cout<<GetPropertyValue["string"]();
return 0;
}
Is this code legal? It compiles but I'm wondering what happens with the return value. Undefined behavior?
class Foo {
public:
void test1() {
}
auto test() -> decltype(test1()) {
return test1(); //<---return void here!
}
};
The code is legal. auto deduces to void and a void function can return another void function. A void function can even
return static_cast<void>("I'm a void");
It's legal, but you can't, for example, assign the result to a variable. [1]
class Foo {
public:
void test1() {
}
auto test() -> decltype(test1()) {
return test1(); //<---return void here!
}
};
int main() {
Foo foo;
auto x = foo.test(); //<---compile error here
}
[1] https://godbolt.org/z/YGAtdJ
I have two functions one of them takes a function as an argument this works just fine, but I want to call this passed function in my second one.
class XY {
public:
void first(void f());
void second();
};
void XY::first(void f()){
}
void XY::second(){
f(); //passed function from first()
}
You might use std::function to store the callable and call it later.
class X {
public:
void set(std::function<void()> f) {
callable = f;
}
void call() const {
callable();
}
private:
std::function<void()> callable;
};
void f() {
std::cout << "Meow" << std::endl;
}
Then create X instance and set the callable:
X x;
x.set(f);
Later call the stored callable:
x.call();
Can a function be assigned or alter its definition, just like overriding a function by derived classes.
But at this time, it is out of scope from the class.
I mean like this:
//class.h
class MClass
{
public:
void function(); // this is the function I am referring to.
}
//class.cpp
void MClass::function() { }
//file1.cpp
MClass mclass;
void globalFunction() { }
mclass.function = globalFunction; //is this even possible?
Your function() is a real function, you want function Callback instead.
see sample program: on ideone
#include <functional>
class MClass
{
public:
std::function<void(void)> func_ptr;
void setFuncPtr(const std::function<void(void)>& ptr)
{
func_ptr = ptr;
}
void callFuncPtr()
{
func_ptr();
}
};
You could set func_ptr to any callabe objet
MClass m;
m.setFuncPtr(globalFunction); // set to standalone function
m.callFuncPtr();
// set lambda to it
m.setFuncPtr([](){ std::cout << " do something " << std::endl; });
m.callFuncPtr();
Or bind to other object
struct Test
{
void print() { std::cout << "Test::print" << std::endl; }
};
Test t;
m.setFuncPtr(std::bind(&Test::print, t));
m.callFuncPtr();
You could also pass parameter to function by using std::bind and placeholders.
There are two ways :
c++03 - you can use function pointer :
class MClass
{
public:
void (*function)();
};
void globalFunction()
{
// ...
}
MClass obj;
mclass.function = globalFunction;
in c++11 you can use functors :
class MClass
{
public:
std::function<void()> function;
};
void globalFunction()
{
// ...
}
MClass obj;
mclass.function = globalFunction;
Following code does NOT work, but it expresses well what I wish to do. There is a problem with the template struct container, which I think SHOULD work because it's size is known for any template argument.
class callback {
public:
// constructs a callback to a method in the context of a given object
template<class C>
callback(C& object, void (C::*method)())
: ptr.o(object), ptr.m(method) {}
// calls the method
void operator()() {
(&ptr.o ->* ptr.m) ();
}
private:
// container for the pointer to method
template<class C>
struct {
C& o;
void (C::*m)();
} ptr;
};
Is there any way to do such a thing? I mean have a non-template class callback which wraps any pointer to method?
Thanks C++ gurus!
Edit:
Please see this:
Callback in C++, template member? (2)
This is a complete working example that does what I think you're trying to do:
#include <iostream>
#include <memory>
// INTERNAL CLASSES
class CallbackSpecBase
{
public:
virtual ~CallbackSpecBase() {}
virtual void operator()() const = 0;
};
template<class C>
class CallbackSpec : public CallbackSpecBase
{
public:
CallbackSpec(C& o, void (C::*m)()) : obj(o), method(m) {}
void operator()() const { (&obj->*method)(); }
private:
C& obj;
void (C::*method)();
};
// PUBLIC API
class Callback
{
public:
Callback() {}
void operator()() { (*spec)(); }
template<class C>
void set(C& o, void (C::*m)()) { spec.reset(new CallbackSpec<C>(o, m)); }
private:
std::auto_ptr<CallbackSpecBase> spec;
};
// TEST CODE
class Test
{
public:
void foo() { std::cout << "Working" << std::endl; }
void bar() { std::cout << "Like a charm" << std::endl; }
};
int main()
{
Test t;
Callback c;
c.set(t, &Test::foo);
c();
c.set(t, &Test::bar);
c();
}
I recently implemented this:
#define UNKOWN_ITEM 0xFFFFFFFF
template <typename TArg>
class DelegateI
{
public:
virtual void operator()(TArg& a)=0;
virtual bool equals(DelegateI<TArg>* d)=0;
};
template <class TArg>
class Event
{
public:
Event()
{
}
~Event()
{
for (size_t x=0; x<m_vDelegates.size(); x++)
delete m_vDelegates[x];
}
void operator()(TArg& a)
{
for (size_t x=0; x<m_vDelegates.size(); x++)
{
m_vDelegates[x]->operator()(a);
}
}
void operator+=(DelegateI<TArg>* d)
{
if (findInfo(d) != UNKOWN_ITEM)
{
delete d;
return;
}
m_vDelegates.push_back(d);
}
void operator-=(DelegateI<TArg>* d)
{
uint32 index = findInfo(d);
delete d;
if (index == UNKOWN_ITEM)
return;
m_vDelegates.erase(m_vDelegates.begin()+index);
}
protected:
int findInfo(DelegateI<TArg>* d)
{
for (size_t x=0; x<m_vDelegates.size(); x++)
{
if (m_vDelegates[x]->equals(d))
return (int)x;
}
return UNKOWN_ITEM;
}
private:
std::vector<DelegateI<TArg>*> m_vDelegates;
};
template <class TObj, typename TArg>
class ObjDelegate : public DelegateI<TArg>
{
public:
typedef void (TObj::*TFunct)(TArg&);
ObjDelegate(TObj* t, TFunct f)
{
m_pObj = t;
m_pFunct = f;
}
virtual bool equals(DelegateI<TArg>* di)
{
ObjDelegate<TObj,TArg> *d = dynamic_cast<ObjDelegate<TObj,TArg>*>(di);
if (!d)
return false;
return ((m_pObj == d->m_pObj) && (m_pFunct == d->m_pFunct));
}
virtual void operator()(TArg& a)
{
if (m_pObj && m_pFunct)
{
(*m_pObj.*m_pFunct)(a);
}
}
TFunct m_pFunct; // pointer to member function
TObj* m_pObj; // pointer to object
};
template <typename TArg>
class FunctDelegate : public DelegateI<TArg>
{
public:
typedef void (*TFunct)(TArg&);
FunctDelegate(TFunct f)
{
m_pFunct = f;
}
virtual bool equals(DelegateI<TArg>* di)
{
FunctDelegate<TArg> *d = dynamic_cast<FunctDelegate<TArg>*>(di);
if (!d)
return false;
return (m_pFunct == d->m_pFunct);
}
virtual void operator()(TArg& a)
{
if (m_pFunct)
{
(*m_pFunct)(a);
}
}
TFunct m_pFunct; // pointer to member function
};
template <typename TArg>
class ProxieDelegate : public DelegateI<TArg>
{
public:
ProxieDelegate(Event<TArg>* e)
{
m_pEvent = e;
}
virtual bool equals(DelegateI<TArg>* di)
{
ProxieDelegate<TArg> *d = dynamic_cast<ProxieDelegate<TArg>*>(di);
if (!d)
return false;
return (m_pEvent == d->m_pEvent);
}
virtual void operator()(TArg& a)
{
if (m_pEvent)
{
(*m_pEvent)(a);
}
}
Event<TArg>* m_pEvent; // pointer to member function
};
template <class TObj, class TArg>
DelegateI<TArg>* delegate(TObj* pObj, void (TObj::*NotifyMethod)(TArg&))
{
return new ObjDelegate<TObj, TArg>(pObj, NotifyMethod);
}
template <class TArg>
DelegateI<TArg>* delegate(void (*NotifyMethod)(TArg&))
{
return new FunctDelegate<TArg>(NotifyMethod);
}
template <class TArg>
DelegateI<TArg>* delegate(Event<TArg>* e)
{
return new ProxieDelegate<TArg>(e);
}
use it like so:
define:
Event<SomeClass> someEvent;
enlist callbacks:
someEvent += delegate(&someFunction);
someEvent += delegate(classPtr, &class::classFunction);
someEvent += delegate(&someOtherEvent);
trigger:
someEvent(someClassObj);
You can also make your own delegates and overide what they do. I made a couple of others with one being able to make sure the event triggers the function in the gui thread instead of the thread it was called.
You need to use polymorphism. Use an abstract base class with a virtual invocation method (operator() if you please), with a templated descendant that implements the virtual method using the correct type signature.
The way you have it now, the data holding the type is templated, but the code meant to invoke the method and pass the object isn't. That won't work; the template type parameters need to flow through both construction and invocation.
#Barry Kelly
#include <iostream>
class callback {
public:
virtual void operator()() {};
};
template<class C>
class callback_specialization : public callback {
public:
callback_specialization(C& object, void (C::*method)())
: o(object), m(method) {}
void operator()() {
(&o ->* m) ();
}
private:
C& o;
void (C::*m)();
};
class X {
public:
void y() { std::cout << "ok\n"; }
};
int main() {
X x;
callback c(callback_specialization<X>(x, &X::y));
c();
return 0;
}
I tried this, but it does not work (print "ok")... why?
Edit:
As Neil Butterworth mentioned, polymorphism works through pointers and references,
X x;
callback& c = callback_specialization<X>(x, &X::y);
c();
Edit:
With this code, I get an error:
invalid initialization of non-const reference of type ‘callback&’
from a temporary of type ‘callback_specialization<X>’
Now, I don't understand that error, but if I replace callback& c with const callback& c and virtual void operator()() with virtual void operator()() const, it works.
You didn't say what errors you found, but I found that this worked:
template<typename C>
class callback {
public:
// constructs a callback to a method in the context of a given object
callback(C& object, void (C::*method)())
: ptr(object,method) {}
// calls the method
void operator()() {
(&ptr.o ->* ptr.m) ();
}
private:
// container for the pointer to method
// template<class C>
struct Ptr{
Ptr(C& object, void (C::*method)()): o(object), m(method) {}
C& o;
void (C::*m)();
} ptr;
};
Note that Ptr needs a constructor as it has a reference member.
You could do without struct Ptr and have the raw members.
Tested with VS2008 express.
Improving the OP's answer:
int main() {
X x;
callback_specialization<X> c(x, &X::y);
callback& ref(c);
c();
return 0;
}
This prints "ok".
Tested on VS2008 express.
Please see this
Callback in C++, template member? (2)