#ifndef __FOREACH_H__
#define __FOREACH_H__
#define in ,
#define ITERATOR(j,S) for(auto j = S.begin(); j != S.end(); ++j)
#ifdef WIN32
#define LL (
#define foreach(...) ITERATOR LL __VA_ARGS__ )
#else
#define foreach(...) ITERATOR(__VA_ARGS__)
#endif
template <typename T, typename F, typename... Args>
void LoopCall(T & t, F f, Args&&... args)
{
foreach(elem in t)
{
using ValueType = typename std::iterator_traits<decltype(elem)>::value_type;
if constexpr (std::is_pointer_v<ValueType>)
{
((*elem)->*f)(std::forward<Args>(args)...);
}
else
{
((*elem).*f)(std::forward<Args>(args)...);
}
}
}
#endif
测试代码如下
#include <iostream>
#include <vector>
#include <list>
#include "foreach.h"
class Data
{
public:
Data(int _age):age(_age) {};
~Data() {
std::cout << "release data" << std::endl;
};
void OnPri

文章介绍了C++中的foreach宏和LOOPCALL模板函数,用于遍历容器并调用成员函数,同时展示了如何处理指针对象。测试代码给出了如何在std::list和std::vector中使用这些功能的例子。
最低0.47元/天 解锁文章
1015





