将定义重写为c++
Rewrite defines as c++
为什么有可能将这两个定义重写为c++代码函数?我想删除#Define
定义1:
#define DO_ALL_BLOCK_IP(iter)
for ((iter) = m_block_ip.begin(); (iter) != m_block_ip.end(); ++(iter))
Define2:
#define DO_ALL_BLOCK_EXCEPTION(iter)
for ((iter) = m_block_exception.begin(); (iter) != m_block_exception.end(); ++(iter))
不直接-如果DO_ALL_BLOCK_IP
是一个函数,那么语法DO_ALL_BLOCK_IP(iter) {/* code here */}
是无效的。
你可以使用新的c++语法范围,只要你不需要直接使用迭代器(只使用值):
for(auto& value : m_block_ip)
{
// code here
}
如果你由于某种原因必须使用一个函数,你可以传递给它一个函子,并使用lambda表达式来定义它:
// definition (assuming m_block_ip is a vector of block_ip_t)
void DO_ALL_BLOCK_IP(std::function<void(std::vector<block_ip_t>::iterator)> f) {
for(auto iter = m_block_ip.begin(); iter != m_block_ip.end(); iter++)
f(iter);
}
// alternate definition that *may* be more efficient, but also more cumbersome
template<class F_CLASS> void DO_ALL_BLOCK_IP(F_CLASS f) {
for(auto iter = m_block_ip.begin(); iter != m_block_ip.end(); iter++)
f(iter);
}
// how to call
DO_ALL_BLOCK_IP([&](std::vector<block_ip_t>::iterator iter) {
// code here
});
宏基本上是一些代码的前缀,这些代码将为一个范围内的每个迭代器做一些事情。虽然你不能做完全相同的使用函数,函数std::for_each
已经几乎做到了这一点;使用lambda函数,它看起来像这样:
std::for_each(nums.begin(), nums.end(),
[](int &n){
// Doing something with an element of nums
// and maybe something else
// In a block that looks pretty much like you would
// use with your macro.
// Note that instead of continue, you'd use return, though.
});
由于这在块上工作,因此不能直接在函数上重写。不幸的是,您需要更改每个用法。
如果DO_ALL_BLOCK_IP
是一个函数,这将无法编译。
DO_ALL_BLOCK_IP(x)
{
// stuff
}
你所能做的只是使用标准库算法或range-for循环(可能使用lambda)。
相关文章:
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- 将OpenCV C++重写为EmguCV C#-如何使用指针
- 在 C++ 中用派生类型重写成员函数
- 在模板基类中为继承类中的可选重写生成虚拟方法
- 方法重写线程C++中的概念
- 为重写std::exception的库生成swig接口时出错
- 如何强制从重写方法调用重写的方法基方法?
- 用于C++的静态二进制检测或二进制重写工具和框架
- 如何将 if else 语句重写为 switch 语句
- 如何重写全局方法名称以在调用原始方法之前将我的代码推到前面
- 用 C 重写C++类
- 是否总是可以将使用递归编写的程序重写为不使用递归的程序C++,性能观点是什么?
- 重写虚拟函数和继承
- C++调用使用重写函数的父类函数
- 重写打印函数而不是覆盖基类
- 不允许在类定义之外重写
- C++有没有办法强制重写一组方法,如果其中一个方法在子类中具有重写?
- C++:从抽象类重写纯虚拟运算符重载
- 派生类调用父类的方法,该方法调用重写的虚拟方法调用错误的方法
- 重写函数不打印基类数据