功能指针数组(包括成员功能)投掷模板专业化错误

Array of function pointers ( including member functions) throwing template specialization error

本文关键字:功能 错误 专业化 指针 数组 包括 成员      更新时间:2023-10-16

所以,我有一个称为委托的类,可以存储一系列函数指针。这是代码:

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 :: Invoke(_callable&amp;&amp;&amp;&amp;,_ types&amp;&amp;&amp; ...)'...)')')

>

但是,当我更改绑定到以下内容的定义时:

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

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

无论如何是否可以解决这个问题?

我需要缓存指针传递的指针。

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