簡體   English   中英

如何創建類似std :: function的包裝器?

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

嘗試這樣做:

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;
}

但是失敗:

 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))'

編譯器為MSVC2013。

應該是這樣的:

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應該專門用於函數簽名類型。 注意: std::function確實更復雜。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM