2016-01-21 85 views
1

嘗試這樣的:如何創建一個std ::函數一樣的包裝?

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。

+2

'MyFunction '看起來像它有一個模板參數 - 一個std ::函數。 「MyFunction 」是做什麼的? – doctorlove

+0

編譯但我想int(int)風格的語法 – paulm

回答

4

它應該是這樣的:

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確實更復雜。

+0

奇怪的是,它的前向聲明爲1 arg,但是接着使用1和var args並將簽名發送到自身?這很讓人困惑:) – paulm

+0

@paulm專業化也需要一個參數,那就是函數簽名 – ForEveR

相關問題