Sorry if this question doesn't make any sense.I don't have much experience with templates. I want to make a generic function which can store a list of static function inside a class and later execute them all.I also need to pass the the reference of objects to each of this function for their execution.I achieved this without using templates
#ifndef _handle_connection
#define _handle_connection
#include <string>
#include <utility>
#include <vector>
#include <errno.h>
#include <iostream>
namespace handle_connection
{
class handleconnection
{
std::vector<std::pair<void *, int (*)(void *, std::string, int)>> funclist;
public:
//adds function to the list of function to excecute
//@param reference of the object
//@param : int (*func)(void* ,std::string,int) function
void use(void *object, int (*func)(void *context, std::string response, int new_socket))
{
funclist.push_back(std::make_pair(object, func));
}
//call
//@param : string response
//@param : int socket
int call(std::string response, int new_socket)
{
for (auto c : funclist)
{
//need to extract the type of the reference object T
if (c.second(c.first, response, new_socket) == 0) //code is incomplete
return 0;
}
return -1;
}
};
} // namespace handle_connection
#endif
class foo
{
std::string path = "it worked for foo";
public:
static int func(void *object, std::string text, int socket);
};
class bar
{
int num = 10;
std::string path = "it worked for bar";
public:
static int func(void *object, std::string text, int socket);
};
int foo::func(void *object, std::string text, int socket)
{
std::cout << static_cast<foo *>(object)->path;
return -1;
}
int bar::func(void *object, std::string text, int socket)
{
std::cout << static_cast<bar *>(object)->path;
return 0;
}
int main()
{
foo obj1;
bar obj2;
handle_connection::handleconnection connections;
connections.use(&obj1, foo::func);
connections.use(&obj2, bar::func);
connections.call("hello", 1);
}
but for this i have to pass void pointer of objects to my function and cast it inside the definition but i dont want to do that.
//not void pointer
template<class T>
void use(void *object, int (*func)(T *context, std::string response, int new_socket))
{
funclist.push_back(std::make_pair(object, func));
//need to store the type information of reference object( T)
//code is incomplete
// i need to store the variable T as well somehow
}
if my understanding of template is not correct can someone tell me what am i thinking wrong.