0

所以,我有一个名为 Delegate 的类,它可以存储一个函数指针数组。这是代码:

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 无法专门化函数模板 'unknown-type std::invoke(_Callable &&,_Types &&...)')

但是当我将 Bind 的定义更改为以下内容时:

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

}

它工作正常,但是当我尝试将函数对象推入向量时,它再次引发相同的错误。

有没有办法解决这个问题?

我需要缓存传入的指针。

4

1 回答 1

1

的结果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)...);
        }
    }
};
于 2016-06-14T16:40:26.607 回答