Jon Stewart on 14 Oct 2003 14:18:23 -0000


[Date Prev] [Date Next] [Thread Prev] [Thread Next] [Date Index] [Thread Index]

Re: [ALACPP] where the boost meets the stl


> On Mon, 2003-10-13 at 23:27, Jon Stewart wrote:
> > Namely, it fills the vector with the numbers 1..20.
> > 
> > My question is, how can you do the same thing with std::fill_n, given its 
> > prototype:
> > 
> > 	template<class OutIt, class Size, class T>
> > 	void fill_n(OutIt first, Size n, const T& x);
> 
> Umm... you don't. I think I don't understand the question. generate &
> fill are meant to do different things. The way fill works,
> operator()=(x) is going to be invoked from first to (first + n). Not
> much wiggle room there for built in types.


<giddy>

You can! Ha-ha! It compiled!! :-)

</giddy>

It's pure, pure chicanery...

#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>

#include <boost/lambda/lambda.hpp>
#include <boost/smart_ptr.hpp>

using namespace boost::lambda;
using namespace std;

template<class FnT>
class Converter {
public:
	Converter(FnT& f) : Fn(f) {}

	operator int() const { // ideally, you deduce this from FnT
		return fn();   // the const is really important
	}
private:
	FnT&	Fn;
};

template<class FnT>
boost::shared_ptr< Converter<FnT> >
MakeConverter(FnT& f)
{
	boost::shared_ptr< Converter<FnT> > ptr(new Converter<FnT>(f));
	return ptr;
}

int main(int argc, char *argv[])
{
	vector<int> vec;
	int i = 0;
	fill_n(back_inserter(vec), 20, *MakeConverter(var(i)++));
	for_each(vec.begin(), vec.end(), cout << _1 << '\n');

	return EXIT_SUCCESS;
}



Jon
-- 
Jon Stewart                                 Advanced Los Angeles C++
stew1@xxxxxxxxxxx                           http://www.alacpp.org
_______________________________________________
alacpp mailing list
alacpp@xxxxxxxxxxx
http://lists.ellipsis.cx/mailman/listinfo/alacpp