
Patrick B. answered 10/05/19
Math and computer tutor/teacher
Specifically, you want to ask some mysterious object if it has a member function with a specific header, prototype, and signature, as you know exactly what arguments need to be passed.
Not for the weak at heart!!!
Member functions are not stored in the class, just the data members.
You will have to try to find some 3rd party compiler tool that will allow you to access the
compiler's internals...so then you can search the symbol table for public member functions...
If you insist on using the template,
the other option and probably the best, is to call the function and somehow catch and handle the exception raised if the function does not exist
public boolean FUNCTION_EXISTS (T * obj)
{
boolean boolReturn = false;
try
{
ret_val = T->FUNCTION_IN_QUESTION( args);
boolReturn = true; //function must exist because it was just called
}
catch(MEMBER_FUNCTION_EXCEPTION)
{
//ouch! the function does not exist, but the program doesn't crash because we got this...
}
return(boolReturn);
}
I see that you are trying to serialize an object...
If that is truly what you are after, you can rethink your logic and
create a pointer to function type that serializes an object...
typdef (char *) SerializerCallback( void *);
Here is an example:
=========================================================
using namespace std;
#include <iostream>
#include <string.h>
#include <stdio.h>
typedef int (*SerializerCallback) (void *, char *);
class Foo
{
private: int X;
double Y;
public:
Foo( int x, double y)
{
X=x; Y=y;
}
int GetX() { return(X); }
double GetY() { return(Y); }
char * ToString( void *)
{
char outbuff[255];
memset(outbuff,0,255);
sprintf(outbuff,"%d,%12.6f",X,Y);
}
};
#define FOO_SIZE (sizeof(class Foo))
class DataRec
{
private:
int X;
double Y;
char str[5];
const int N=5;
public:
DataRec( int x, double y, char * s)
{
X=x;
Y = y;
strncpy(str,s,N);
}
int GetX(){ return(X); }
double GetY() { return(Y); }
char * GetStr() { return(str); }
};
#define DATAREC_SIZE (sizeof(class DataRec))
int FooSerializer ( void * obj, char * outbuff)
{
Foo * foo = (Foo *)obj;
memset(outbuff,0,FOO_SIZE+1);
sprintf(outbuff,"%d,%12.6f",foo->GetX(),foo->GetY());
return(0);
}
int DataRecSerializer ( void * obj, char * outbuff)
{
DataRec * dataRec = (DataRec *)obj;
memset(outbuff,0,DATAREC_SIZE+1);
sprintf(outbuff,"%d,%12.6f,%s",dataRec->GetX(),dataRec->GetY(),dataRec->GetStr());
return(0); //caller must delete the memory
}
int main()
{
Foo * myFoo = new Foo(711,35.42);
char fooOutBuff[FOO_SIZE+1];
DataRec * myDataRec = new DataRec(6977,42.35,"TEST");
char dataRecOutBuff[DATAREC_SIZE+1];
SerializerCallback serializerCallbackFunc = FooSerializer;
serializerCallbackFunc((void *)myFoo,fooOutBuff);
serializerCallbackFunc = DataRecSerializer;
serializerCallbackFunc((void*)myDataRec,dataRecOutBuff);
std::cout << fooOutBuff << endl;
std::cout << dataRecOutBuff << endl;
}