[英]Array of function pointers ( including member functions) throwing template specialization error
So, I have a class called Delegate that can store an array of function pointers. 因此,我有一个名为Delegate的类,可以存储函数指针数组。 This is the code: 这是代码:
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)...);
}
}
};
Usage in Player.cpp: Player.cpp中的用法:
delegate<void(float)> testDelegate;
testDelegate.Bind(std::bind(&Player::MoveLeft,this));
This throws the error C2893 (Error C2893 Failed to specialize function template 'unknown-type std::invoke(_Callable &&,_Types &&...)') 这将引发错误C2893(错误C2893无法专门化功能模板'unknown-type std :: invoke(_Callable &&,_ Types && ...)')
But when I change the definition of Bind to the following: 但是,当我将“绑定”的定义更改为以下内容时:
template<typename F>
void Bind(F f)
{
}
It works fine, but when I try to push the function object into the vector it throws the same error again. 它工作正常,但是当我尝试将函数对象推入向量时,它将再次引发相同的错误。
Is there anyway to resolve this? 反正有解决办法吗?
I need to cache the pointers passed in. 我需要缓存传入的指针。
The result of std::bind
is not a function pointer (it is a function object of an unspecified type), but you're trying to make it into one. std::bind
的结果不是函数指针(它是未指定类型的函数对象),但是您试图将其变成一个。 Since you're using std::forward
, you must be using C++11, which means you can use std::function
: 由于您使用的是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)...);
}
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.