问题描述
在C ++中,有可能做一些类型的通用函数指针,指向返回一个类型的指针并且不带参数的任何函数。
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 of pointer that can point to both of the following:
int* funcInt(){
int* i = new int;
*i = 5;
return i;
}
char* funcChar(){
char* c = new char;
*c = 'a';
return c;
}
显然以下是有效的:
int* (*funcPointerA)() = funcInt;
char* (*funcPointerB)() = funcChar;
但是可以做类似下面的事情(它给出了编译错误)
But is it possible to do something like the following (it gives a compile error at the moment):
void* (*funcPointerC)() = funcInt;
void* (*funcPointerD)() = funcChar;
目前上述代码给出以下错误:
Currently the above code gives the following error:
error: invalid conversion from 'int* (*)()' to 'void* (*)()'
error: invalid conversion from 'char* (*)()' to 'void* (*)()'
funcPointerA和B到C和D?
Is there any way to cast the funcPointerA and B to C and D?
这样就可以将指针指向两种类型的函数(以及在没有参数的情况下返回指向某种类型的指针的指针)可以一起存储在单个向量中。 p>
This is so pointers to both types of functions (and others that return a pointer to some type while taking no arguments) can be stored together in a single vector.
推荐答案
标准不允许这样的事情。你可能也可能不能把函数指针转换为 void *(*)()
。在C ++中有符合标准的解决方案。这里是一个简单的前C ++ 11一个:
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;
};
现在您可以存储 shared_ptr< Myfunc>
在C ++ 11中更好的解决方案可能如下所示:
A much nicer solution in C++11 could look like this:
template <typename T>
std::function<void*()> castToVoidFunc (T* (*func)())
{
return [=](){ return func(); };
}
这篇关于C ++有可能有一个通用的函数指针吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!