在堆上生成对象的函数式编程技术
有一个在堆上生成 N 个 A 类对象的代码示例:
#include <vector>
#include <iostream>
#include <algorithm>
#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>
using boost::make_shared;
using boost::shared_ptr;
class A
{
int val_;
public:
explicit A(int i) : val_(i) {}
int foo() const { return val_;}
};
template<typename T>
struct Generator
{
shared_ptr<T> operator()()
{
return make_shared<T>(std::rand() % 10 + 1);
}
};
int main()
{
std::vector< shared_ptr<A> > coll;
std::generate_n( back_inserter(coll), 3, Generator<A>());
std::vector<shared_ptr<A> >::const_iterator cit;
for (cit = coll.begin(); cit != coll.begin(); ++cit)
std::cout << (*cit)->foo() << std::endl;
return 0;
}
代码使用函子“Generator”和“generate_n”算法来完成这项工作。我对这项任务的简化感到不安。 boost:lambda、boost::phoenix 是可能的候选者(如果是的话?),该怎么做?或者也许还有其他选择?
There is example of code which generates N objects of class A on the heap:
#include <vector>
#include <iostream>
#include <algorithm>
#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>
using boost::make_shared;
using boost::shared_ptr;
class A
{
int val_;
public:
explicit A(int i) : val_(i) {}
int foo() const { return val_;}
};
template<typename T>
struct Generator
{
shared_ptr<T> operator()()
{
return make_shared<T>(std::rand() % 10 + 1);
}
};
int main()
{
std::vector< shared_ptr<A> > coll;
std::generate_n( back_inserter(coll), 3, Generator<A>());
std::vector<shared_ptr<A> >::const_iterator cit;
for (cit = coll.begin(); cit != coll.begin(); ++cit)
std::cout << (*cit)->foo() << std::endl;
return 0;
}
Code uses functor "Generator" and "generate_n" algorithm to do the job. I wounder about simplification of this task. boost:lambda, boost::phoenix are possible candidates (if they are?), and how to do it? Or maybe there are other alternatives?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
简单的做法是不要在第一种情况下使问题变得复杂:
每种不同的范式都有其优点和缺点,在这种情况下,在 C++ 中,尝试强制使用函数式方法来解决问题将使事情变得比他们需要的更复杂。
通过编译器中的 lambda 支持,您可以执行以下操作:
Simple would be not to convolute the problem in the first case:
Each different paradigm has its strengths and weaknesses, and in this case, in C++, trying to force a functional approach to the problem will make things more complex than they need be.
With lambda support in the compiler you could do: