简体   繁体   English

从函数类型声明中推导出函数参数,用于模板结构方法?

[英]Deduce Function Arguments From A Function Type Declare, For Templated Struct Method?

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!提前致谢!

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):简单的解决方案是让编译器推断返回类型并让调用者传递正确的类型(如果不传递则编译失败):

template<class T>
struct _function_wrapper_t
{
    template <typename ...U>
    auto call(U&&... t)
    {
        return m_pfnFunc(std::forward<U>(t)...);
    }

    T m_pfnFunc;
};

If you do not like that you can use partial specialization:如果您不喜欢这样,您可以使用部分专业化:

template<class T>
struct _function_wrapper_t;

template <typename R,typename...Args>
struct _function_wrapper_t<R(*)(Args...)>
{
    R call(Args...args)
    {
        return m_pfnFunc(args...);
    }
    using f_type = R(*)(Args...);
    f_type m_pfnFunc;
};

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. PS:在后一种情况下也可以进行完美转发,但它需要一些样板文件,为了简洁起见,我省略了一些样板文件。

Check the std::function implementation.检查std::function实现。 It seems it does what you need:看来它可以满足您的需要:

#include <functional>

int MultiplyTwoNumbers(int nNum, int nNum2)
{
    return nNum * nNum2;
}

int MultiplyThreeNumbers(int nNum, int nNum2, int pnNum3)
{
    return nNum * nNum2 * pnNum3;
}

int main()
{
    std::function<decltype(MultiplyTwoNumbers)> two = &MultiplyTwoNumbers;
    std::function<decltype(MultiplyThreeNumbers)> three = &MultiplyThreeNumbers;

    auto ret1 = two(1, 2);
    auto ret2 = three(4, 5, 8);

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM