C++11尝鲜:Variadic Function Templates(带变长参数的函数模板)(续)

11 篇文章 0 订阅

代码1

#include <iostream>
#include <string>
#include <boost/ref.hpp>
#include <boost/fusion/container.hpp>
#include <boost/fusion/algorithm.hpp>
#include <boost/lambda/lambda.hpp>
using namespace std;
using namespace boost::fusion;
using namespace boost::lambda;

template<typename First, typename... Rest>
void output(First const& first, Rest const&... rest)
{
    cout << first;
    auto v = make_vector(boost::cref(rest)...);
    for_each(v, cout << constant(',') << _1);
    cout << endl;
}

template<typename First, typename... Rest>
First sum(First first, Rest const&... rest)
{
    auto v = make_vector(boost::cref(rest)...);
    for_each(v, var(first) += _1);
    return first;
}

int main()
{
    double d = 2.3;
    output(42,"hello",d,'a');
    output("hello",d,'a');
    output(d,'a');
    output('a');
    output(sum(1), sum(1, 2), sum(string(), 'a', 'b'));
    return 0;
}

//42,hello,2.3,a
//hello,2.3,a
//2.3,a
//a
//1,3,ab


代码2

// filename: a.cpp

#ifndef BOOST_PP_IS_ITERATING

#include <iostream>
#include <string>
#include <boost/ref.hpp>
#include <boost/fusion/container.hpp>
#include <boost/fusion/algorithm.hpp>
#include <boost/lambda/lambda.hpp>
using namespace std;
using namespace boost::fusion;
using namespace boost::lambda;

#define BOOST_PP_ITERATION_PARAMS_1   (3, (1, 5, "a.cpp"))
#include BOOST_PP_ITERATE()

int main()
{
	double d = 2.3;
	output(42,"hello",d,'a');
	output("hello",d,'a');
	output(d,'a');
	output('a');
	output(sum(1), sum(1, 2), sum(string(), 'a', 'b'));
	return 0;
}

//42,hello,2.3,a
//hello,2.3,a
//2.3,a
//a
//1,3,ab

#else

#define N BOOST_PP_ITERATION()
#define MACRO_CREF(z, n, t) boost::cref(BOOST_PP_CAT(t, n))

template<BOOST_PP_ENUM_PARAMS(N, typename T)>
void output(BOOST_PP_ENUM_BINARY_PARAMS(N, T, const& t))
{
	cout << t0;
	auto v = make_vector(BOOST_PP_ENUM_SHIFTED(N, MACRO_CREF, t));
	//boost::fusion::vector<BOOST_PP_ENUM_SHIFTED_BINARY_PARAMS(N, T, const& BOOST_PP_INTERCEPT)> v = make_vector(BOOST_PP_ENUM_SHIFTED(N, MACRO_CREF, t));
	for_each(v, cout << constant(',') << _1);
	cout << endl;
}

template<BOOST_PP_ENUM_PARAMS(N, typename T)>
T0 sum(T0 t0 BOOST_PP_COMMA_IF(BOOST_PP_NOT_EQUAL(N, 1)) BOOST_PP_ENUM_SHIFTED_BINARY_PARAMS(N, T, const& t))
{
	auto v = make_vector(BOOST_PP_ENUM_SHIFTED(N, MACRO_CREF, t));
	//boost::fusion::vector<BOOST_PP_ENUM_SHIFTED_BINARY_PARAMS(N, T, const& BOOST_PP_INTERCEPT)> v = make_vector(BOOST_PP_ENUM_SHIFTED(N, MACRO_CREF, t));
	for_each(v, var(t0) += _1);
	return t0;
}

#undef N
#endif


评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值