看到Unity的代表和事件,我试图编写我自己的代码: 我想用variadic模板创建一个类,指定函数的返回类型和optionals参数。C++模板化代表像Unity一样
template <typename Ret, typename... Args>
class MyDelegate{
std::vector<Ret(*)(Args...)> vec;
public:
void operator+=(const Ret(*)(Args...)& newElement)
{
vec.push_back(newElement);
}
Ret operator()(const Args&... args)
{
for (auto i = vec.begin(); i != vec.end(); ++i)
(*i)(args...);
}
};
正如你可以看到,我想这个类这样使用:
MyDelegate<void> voidDelegate;
MyDelegate<void, int> intDelegate;
MyDelegate<int, char, boolt> miscDelegate;
并使用+ =运营商,如 “加入” 功能分配到每个之一:
voidDelegate += voidFunc;
//etc...
我现在遇到+ =运算符的问题,因为VS不接受这个:
MyDelegate<void, int> delegate1;
delegate1 += [](const int a)->void{std::cout << a << std::endl; };
lambda函数是正确的:它需要一个int并返回void,所以我不明白最新的错误。
紧密相关的话题(延迟调度),你会发现[**这个问题,和顶级的答案**](http://stackoverflow.com/ a/7858971/1322972)特别有趣。它无时无刻地为我派上用场。 – WhozCraig