可变参数好像很厉害的样子,会节省很多手写代码,让编译器自动帮我们生成代码
template<typename Fun, typename...Args>
void invoke(Fun&& fun, Args&&...args)
{
fun(std::forward<Args>(args)...);
}
任意函数包装器,搞个面向切面,代理,信手拈来
仿照C#的委托
template<typename Fun>
class my_delegate
{
public:
my_delegate(){}
~my_delegate(){}
template<typename...Args>
void operator()(Args&&...args) {
for (auto i : m_funs)
{
i(std::forward<Args>(args)...);
}
}
void append(Fun&& cb)
{
m_funs.push_back(std::move(cb));
}
my_delegate& operator+(Fun cb)
{
m_funs.push_back(std::move(cb));
return *this;
}
my_delegate& operator+=(Fun cb)
{
m_funs.push_back(std::move(cb));
return *this;
}
my_delegate& operator-=(Fun cb)
{
auto it = find(m_funs.begin(), m_funs.end(), cb);
if (it != m_funs.end())
m_funs.erase(it);
return *this;
}
private:
std::vector<Fun> m_funs;
};
typedef void (*Fun)(int sender, int params);
void button_click(int sender, int params)
{
std::cout << "invoke " << __FUNCTION__ << std::endl;
std::cout << "sender = " << sender << " params = " << params << std::endl;
}
void button_other_event_handler(int sender, int params)
{
std::cout << "invoke " << __FUNCTION__ << std::endl;
std::cout << "sender = " << sender << " params = " << params << std::endl;
}
int main() {
my_delegate<Fun> delegate_obj;
delegate_obj += button_click;
delegate_obj += button_other_event_handler;
delegate_obj(0, 0);
delegate_obj -= button_click;
delegate_obj(10, 20);
return 0;
}文章来源:https://www.toymoban.com/news/detail-685874.html
还停留在老掉牙的C++的认知上,看了一些C++11的新特性,会不会激发对C++的新兴趣?文章来源地址https://www.toymoban.com/news/detail-685874.html
到了这里,关于会不会激发对modern c++的新兴趣的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!