In C++ is it possible to make some sort of generic function pointer that points to any function that returns a pointer to some type and takes no arguments?
Eg, one type
The standard does not allow such thing. You may or may not be able to get away with casting your function pointer to void* (*)()
. In C++ there are standard-conforming solutions. Here is a simple pre-C++11 one:
struct MyFunc
{
virtual void* operator()() = 0;
virtual ~Myfunc(){}
};
template <typename T>
struct MyfuncImpl
{
typedef T TFunc();
MyfuncImpl (TFunc* func) : m_func(func) {}
void* operator()() { return m_func(); }
private:
TFunc* m_func;
};
Now you can store shared_ptr<Myfunc>
in your vector.
A much nicer solution in C++11 could look like this:
template <typename T>
std::function<void*()> castToVoidFunc (T* (*func)())
{
return [=](){ return func(); };
}
Is there any way to cast the funcPointerA and B to C and D?
Yes, you can explicitly cast one type of function pointer to another type:
void* (*funcPointerC)() = reinterpret_cast<void*(*)()>(funcInt);
But it is undefined behaviour to call the result of the cast, you must cast it back to its original type first. If you can record the original type and arrange for the pointer to be cast back to that original type then your code can work.