淘先锋技术网

首页 1 2 3 4 5 6 7

改造print

    C++中有两种比较常见的输出方法,一是利用cout进行流输出,另一种是利用从C中继承的stdio.h库中的printf()函数。如果不考虑运行速度和溢出等问题,cout还是有一个明显优势的——基本不用考虑输出的参数类型。如果调用printf(),则需要考虑输出内容的参数,并予以不同的标记。但是,如果在泛型编程中,不明确类型,则很难使用printf()进行输出。为此,我们利用泛型,结合cout,创造出一个新的函数——print()。类似于Python,您可以向该函数传入任意数量任意类型的参数,比如print(“C++”, ‘a’, 125, 5.98)。
    实现这个print的思路是运用递归。每次调用时,只使用cout输出一个参数,然后接着调用,直到没有参数可以调用为止。但由于使用了cout,这个函数的调用会导致编译和运行速度不及printf。

实现代码:

void print () { };
template <typename T, typename ...OtherTypes>
void print (const T& __arg, const OtherTypes&... __args)
{
    cout << __arg;
	print (__args...);
}

测试代码:

// 需要C++11标准及以上。
# include <iostream>
using namespace std;

void print () { };
template <typename T, typename ...OtherTypes>
void print (const T& __arg, const OtherTypes&... __args)
{
    cout << __arg;
	print (__args...);
}

int main()
{
	int a = 125;
	double d = 5.20;
	char c = 'a';
	string s = "string字符串";
	print(a, d, c, s, "\n");
	return 0;
}

应当输出:

1255.2astring-字符串