Containers of Generic Function Pointers

I

inquisitive

Is there a way to create a collection of Method objects, for example a
vector or a list?

template <typename elemType>
struct Method
{
bool (*function)(elemType&);

template <typename elemType>
inline bool operator()(elemType & property)
{
return function(property);
}
};

so that I can do something like:

int main()
{
std::string property;

std::vector <Method> methodList;

Method method;

method.function = someMethod;

methodList.push_back(method);

method.function = someOtherMethod;

methodList.push_back(method);

std::vector<Method>::iterator it;

for(it = methodList.begin(); it != methodList.end(); it++)
{
std::cout << "Value: " << ((*it)(property)) << std::endl;
}

return 0;
}

bool someMethod(int & value)
{
value = 25;

return true;
}

bool someOtherMethod(std::string & value)
{
value = "Hello, World!";

return true;
}
 
T

Triple-DES

Is there a way to create a collection of Method objects, for example a
vector or a list?

Not the way you want. See comments below. See also my previous reply.
template <typename elemType>
struct Method
{
    bool (*function)(elemType&);

    template <typename elemType>
    inline bool operator()(elemType & property)
    {
        return function(property);
    }

};

so that I can do something like:

int main()
{
    std::string property;

    std::vector <Method> methodList;

Which Method? Methods with different elemTypes are different types.
You can not store different types directly in a vector.
    Method method;

    method.function = someMethod;

For this to work said:
    methodList.push_back(method);

    method.function = someOtherMethod;

which it said:
    methodList.push_back(method);

    std::vector<Method>::iterator it;

    for(it = methodList.begin(); it != methodList.end(); it++)
    {
       std::cout << "Value: " << ((*it)(property)) << std::endl;

    }

   return 0;

}

bool someMethod(int & value)
{
    value = 25;
    return true;
}

bool someOtherMethod(std::string & value)
{
    value = "Hello, World!";
    return true;
}

Sorry I couldn't be of more help.

DP
 
I

inquisitive

Thanks to both of you.

I suspected that I was assuming something which is fundamentally not
possible, but got lost in the templates. Thanks for conforming.
 

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,020
Latest member
GenesisGai

Latest Threads

Top