2016-06-14 63 views
0

的所以,我有一类称为代表能够存储函数指针阵列。这是代码:阵列的函数指针(包括成员函数)投掷模板特错误

template<typename Func> 
class delegate 
{ 
private: 
public: 
    typename std::vector<Func> mListOfFunctions; 
    void Bind(Func f) 
    { 
     mListOfFunctions.push_back(f); 
    } 
    template<typename...TArgs> 
    void Invoke(TArgs&&...arg) 
    { 
     for (auto f : mListOfFunctions) 
     { 
      f(std::forward<TArgs>(arg)...); 
     } 
    } 
}; 

用法在Player.cpp:

delegate<void(float)> testDelegate; 
testDelegate.Bind(std::bind(&Player::MoveLeft,this)); 

这引发错误C2893(错误C2893无法专注函数模板“未知类型的std ::调用(_Callable & & ,_types & & ...)“)

但是,当我更改绑定的定义如下:

template<typename F>  
void Bind(F f) 
    { 

    } 

它工作正常,但是当我试图函数对象推到载体中再次抛出了同样的错误。 无论如何要解决这个问题吗?我需要缓存通过的指针

回答

0

std::bind的结果不是一个函数指针(它是一个未指定类型的函数对象),但你试图将它合并为一个。由于您使用的std::forward,您必须使用C++ 11,这意味着你可以使用std::function

template<typename Func> 
class delegate 
{ 
private: 
public: 
    typename std::vector<std::function<Func>> mListOfFunctions; 
    void Bind(std::function<Func> f) 
    { 
     mListOfFunctions.push_back(f); 
    } 
    template<typename...TArgs> 
    void Invoke(TArgs&&...arg) 
    { 
     for (auto f : mListOfFunctions) 
     { 
      f(std::forward<TArgs>(arg)...); 
     } 
    } 
}; 
+0

我改成了下面的,它仍然抛出一个错误:无效绑定(标准::功能<返回类型(TArgs ...)> F) \t { \t \t mListOfFunctions.push_back(F); \t} –

+0

为什么要那样做?为什么你不使用我发布的代码? –

+0

我这样做太:模板 类委托 { 私人: 市民: \t类型名称的std ::向量<性病::功能> mListOfFunctions; \t空隙绑定(标准::函数 F) \t { \t \t mListOfFunctions.push_back(F); \t} \t模板<类型名... TArgs> \t空隙调用(TArgs && ... ARG) \t { \t \t为(自动F:mListOfFunctions) \t \t { \t \t \t F(标准::转发(arg)...); \t \t} \t} };但是当我调用绑定时,它会再次抛出错误 –