vector of generic function pointers

I

inquisitive

Is it possible to have a vector of generic function pointers?

I am able to devise a generic function pointer, this way:

template <typename elemType, elemType (*function)(std::string&)>
struct Method
{
inline elemType operator()(std::string & property)
{
return function(property);
}
};

It is instantiated as:
Method <int, methodOne> numberMethod;

Now I want to create a vector of these generic function pointers, how
do I declare such a vector and how do I initialize its elements:

I found this Scott Meyer's link, which maybe helpful - it is giving me
hint but I am not able to gain my solution from it: http://www.ddj.com/cpp/184401580
 
T

Triple-DES

Is it possible to have a vector of generic function pointers?

I am able to devise a generic function pointer, this way:

template <typename elemType, elemType (*function)(std::string&)>
struct Method
{
    inline elemType operator()(std::string & property)
    {
        return function(property);
    }

};

It is instantiated as:
 Method <int, methodOne> numberMethod;

Now I want to create a vector of these generic function pointers, how
do I declare such a vector and how do I initialize its elements:

You could make a common base class:

template<typename E>
struct MethodBase
{
virtual E operator()(const std::string&) const = 0;
};
template<typename E, E(*f)(const std::string&)>
struct Method : public MethodBase<E>
{
// ...
};

int main()
{
std::vector<MethodBase<int> *> v;
v.push_back( new M<int, someFunction>);
v.push_back( new M<int, someFunction2>);
// cleanup
}
 
I

inquisitive

You could make a common base class:

template<typename E>
struct MethodBase
{
virtual E operator()(const std::string&) const = 0;};

template<typename E, E(*f)(const std::string&)>
struct Method : public MethodBase<E>
{
// ...

};

int main()
{
std::vector<MethodBase<int> *> v;
v.push_back( new M<int, someFunction>);
v.push_back( new M<int, someFunction2>);
// cleanup

}

Thank you, but I want the independence to have different return-types
for my functions.

The problem that I was facing is to as to how could I templatize the
parameter passed on to the vector at its declaration.
My core issue is to create a generic function pointers with the
signature known in advance but not the actual type of the parameter
and return value. And then how do I build a collection of such generic
function pointers.

A second question is, if the vector and the functions are part of a
class, how would the declaration look like.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,008
Latest member
HaroldDark

Latest Threads

Top