2016-01-21 71 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

相关问题