Boost开发指南-4.2ignore_unused

ignore_unused

编写代码的过程中有时会出现一些暂时用不到但又必须保留的变量,GCC等编译器会对此发出警告,使用-Wunused可以关闭这些警告消息,不过这也有可能导致潜在的隐患。古老的办法是使用(void)var的形式来“使用”一下变量,但这种方法含义不明确,不利于维护。

Boost程序库的 ignore_unused 组件就这个问题给出了更好的解决方案。它原本是proto库里的一个小工具,因为在Boost很多其他库中都被使用,所以在增强了功能后被“扶正”。

ignore_unused位于名字空间boost,为了使用ignore_unused库,需要包含头文件<boost/core/ignore_unused.hpp>,即

#include <boost/core/ignore_unused.hpp>
using namespace boost;

基本用法

ignore_unused的实现非常地简单,几乎什么也没有做:

template <typename...Ts>
inline void ignore_unused(Ts const&...)
{
    
    }

ignore_unused使用可变参数模板,可以支持任意数量、任意类型的变量,把它们作为函数的参数“使用”了一下,“骗”过了编译器,达到了与(void)var 完全相同的效果。但它的命名更清晰,写法也更简单,而且由于是inline函数,完全没有运行时的效率损失。

假设我们有如下的一个函数,出于某种原因,它没有使用参数x,并且声明了一个暂未使用的变量:

int func(int x, int y)
{
    
    
    int i; //未使用的变量i
    return y; //未使用函数参数x
}

GCC在编译代码时会报出警告信息:

In function 'int func(int, int) " :
warning : unused variable 'i'[一Wunused-variable]

At global scope :
warning: unused parameter 'x,[-Wunused-parameter]
int func(int x, int y)

使用ignore_unused我们可以显式地忽略这些变量,从而轻易地消除这些警告信息:

int func(int x, int y)
{
    
    
	int i;

	ignore_unused(x, i); //相当于(void)x;(void)i;
 
	return y;
}

显然,ignore_unused 比 C风格的(void) var要更容易理解,无需多余的注释,代码自身说明了一切。

模板用法

ignore_unused库还可以作用于未使用的局部类型定义,它的另一种形式是:

template<typename...Ts>
inline void ignore_unused() //注意没有函数参数列表
{
    
    }

ignore_unused的模板用法与函数用法类似,但它不需要函数参数,而是在模板参数列表里写出要忽略的类型。

例如下面的函数内部定义了一个typedef,然后用ignore_unused忽略之:

void func2()
{
    
    
	typedef int result_type; //暂未使用的类型定义
	ignore_unused<result_type>(); //忽略未使用的类型定义
}

代码示例

#include <boost/core/ignore_unused.hpp>
using namespace boost;

//
int func(int x, int y)
{
    
    
	int i;

	ignore_unused(x, i);

	return y;
}

//
void func2()
{
    
    
	typedef int result_type;
	ignore_unused<result_type>();
}


int main()
{
    
    
	//func(1, 2);
}

猜你喜欢

转载自blog.csdn.net/qq_36314864/article/details/132101033