将定义重写为c++

Rewrite defines as c++

本文关键字:c++ 重写 定义      更新时间:2023-10-16

为什么有可能将这两个定义重写为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)。