Search code examples
c++functortemplate-classes

c++ store functor in class


I´ve created the following Event class:

Event.h

#ifndef EVENT_H
#define EVENT_H

#include<string>

template<typename T>
class Event
{
    public:
        T fnktptr; //Error: field ‘Event<int()>::fnktptr’ invalidly declared function type
        Event();
        virtual ~Event();
};

#endif // EVENT_H

Event.cpp

#include "Event.h"

template<typename T>
Event<T>::Event()
{
    //ctor
}
template<typename T>
Event<T>::~Event()
{
    //dtor
}
// No need to call this TemporaryFunction() function,
// it's just to avoid link error.
void TemporaryFunction ()
{
    Event<int> TempObj;
}

Now I tested it with the following code and it works:

Event<int> event;
int t = 5;
event.fnktptr = t;

But finally, I want to use it with a functor like this:

Event<decltype(consumeInt)> event;
event.fnktptr = consumeInt;

But now I get a Error in the Event.h file:

T fnktptr; //Error: field ‘Event<int()>::fnktptr’ invalidly declared function type

Solution

  • Based on your latest comments, I would say a std::function<> is the best way forward. The example code below assumes you just want to call fnktptr and don't care about the result.

    #include <functional>
    
    class Event
    {
        public:
            std::function<void ()> fnktptr;
            Event();
            virtual ~Event();
    };
    

    If you need to capture the result, you will not be able to arbitrarily have different returns for each Event object. You either must pick one or use something like boost::variant<>.

    template<class T>
    class Event
    {
        public:
            std::function<T ()> fnktptr;
            Event();
            virtual ~Event();
    };
    

    This would allow you to create Event<int> objects for instance to use with consumeInt().

    Example:

    Event<int> event;
    event.fnktptr = consumeInt;