从函数类型声明中推导函数参数,用于模板结构方法?
我想知道是否可以推断出返回类型,以及来自函数类型的参数定义。
我希望做类似的事情:
template<class T>
struct _function_wrapper_t
{
[return of T] call([Args of T]....)
{
return (T)m_pfnFunc(Args);
}
void* m_pfnFunc;
};
int MultiplyTwoNumbers(int nNum, int nNum2)
{
return nNum * nNum2;
}
int MultiplyThreeNumbers(int nNum, int nNum2, int* pnNum3)
{
return nNum * nNum2 * *pnNum3;
}
int main()
{
_function_wrapper_t<decltype(&MultiplyTwoNumbers)> two(&MultiplyTwoNumbers);
_function_wrapper_t<decltype(&MultiplyThreeNumbers)> three(&MultiplyThreeNumbers);
auto ret1 = two.call(1, 2);
auto ret2 = three.call(4, 5, 8);
}
但是,我不确定是否可以从类型的函数指针中辨别返回类型和函数参数。
如果您确实说
typedef void*(__cdecl* fnOurFunc_t)(const char*, int, float**);
编译器知道将来将其用作类型,那么它是否进一步适用于模板?这是非常特定的用例所需的。
提前致谢!
I was wondering if it was possible to deduce the return type, and parameters from a function type define.
I was hoping to do something similar:
template<class T>
struct _function_wrapper_t
{
[return of T] call([Args of T]....)
{
return (T)m_pfnFunc(Args);
}
void* m_pfnFunc;
};
int MultiplyTwoNumbers(int nNum, int nNum2)
{
return nNum * nNum2;
}
int MultiplyThreeNumbers(int nNum, int nNum2, int* pnNum3)
{
return nNum * nNum2 * *pnNum3;
}
int main()
{
_function_wrapper_t<decltype(&MultiplyTwoNumbers)> two(&MultiplyTwoNumbers);
_function_wrapper_t<decltype(&MultiplyThreeNumbers)> three(&MultiplyThreeNumbers);
auto ret1 = two.call(1, 2);
auto ret2 = three.call(4, 5, 8);
}
However I'm not sure if its possible to discern the return type and function arguments from a type of function pointer.
if you did say
typedef void*(__cdecl* fnOurFunc_t)(const char*, int, float**);
The compiler knows to use that as the type in the future, does the same apply further to templates? This is needed for a VERY specific use case.
Thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
简单的解决方案是让编译器推断返回类型,并让呼叫者通过正确的类型(在不这样做时无法编译):
如果您不喜欢那样,则可以使用部分专业化:
实时演示
ps:在后一种情况下也可以进行完美的转发,但它需要一些我为了简化而遗漏的样板。
The simple solution is to let the compiler deduce return type and let the caller pass the right types (and fail to compile when they don't):
If you do not like that you can use partial specialization:
Live Demo
PS: perfect forwarding is also possible in the latter case but it requires some boilerplate that I left out for the sake of brevity.
检查
std ::功能
实现。看来它可以做您需要的事情:Check the
std::function
implementation. It seems it does what you need: