简体   繁体   English

如何创建类似std :: function的包装器?

[英]How to create a std::function alike wrapper?

Attempted this: 尝试这样做:

template <class R, class... Ts>
class MyFunction
{
public:
    using func_type = R(*)(Ts...);

    MyFunction(func_type f)
      : m_func(f) 
    {
    }

    R operator()(Ts ... args) 
    {
        return m_func(args...);
    }

private:
    func_type m_func;
};

int Testfn(int a)
{
    std::cout << "value is " << a;
    return 42;
}

void Testing()
{
    MyFunction<int(int)> func(Testfn);
    std::cout << "Ret is " << func(1) << std::endl;
}

But fails with: 但是失败:

 error C2064: term does not evaluate to a function taking 1
 C2091: function returns function   
 C2091: function returns
 C2664: 'MyFunction<int (int),>::MyFunction(const MyFunction<int
 (int),> &)' : cannot convert argument 1 from 'int (__cdecl *)(int)' to
 'int (__cdecl *(__cdecl
 *)(void))'

Compiler is MSVC2013. 编译器为MSVC2013。

It should be like this: 应该是这样的:

template <typename T>
class MyFunction;

template<typename R, class... Ts>
class MyFunction<R(Ts...)>
{
public:
    using func_type = R(*)(Ts...);

    MyFunction(func_type f)
      : m_func(f) 
    {
    }

    R operator()(Ts ... args) 
    {
        return m_func(args...);
    }

private:
    func_type m_func;
};

MyFunction should be specialized for function signature type. MyFunction应该专门用于函数签名类型。 Note: std::function is really more complicated. 注意: std::function确实更复杂。

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

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