// ... snipped includes for iostream and fusion ...
namespace fusion = boost::fusion;
class Base
{
protected: int x;
public: Base() : x(0) {}
void chug() {
x++;
cout << "I'm a base.. x is now " << x << endl;
}
};
class Alpha : public Base
{
public:
void chug() {
x += 2;
cout << "Hi, I'm an alpha, x is now " << x << endl;
}
};
class Bravo : public Base
{
public:
void chug() {
x += 3;
cout << "Hello, I'm a bravo; x is now " << x << endl;
}
};
struct chug {
template<typename T>
void operator()(T& t) const
{
t->chug();
}
};
int main()
{
typedef fusion::vector<Base*, Alpha*, Bravo*, Base*> Stuff;
Stuff stuff(new Base, new Alpha, new Bravo, new Base);
fusion::for_each(stuff, chug()); // Mutates each element in stuff as expected
/* Output:
I'm a base.. x is now 1
Hi, I'm an alpha, x is now 2
Hello, I'm a bravo; x is now 3
I'm a base.. x is now 1
*/
cout << endl;
// If I don't put 'const' in front of Stuff...
typedef fusion::result_of::push_back<const Stuff, Alpha*>::type NewStuff;
// ... then this complains because it wants stuff to be const:
NewStuff newStuff = fusion::push_back(stuff, new Alpha);
// ... But since stuff is now const, I can no longer mutate its elements :(
fusion::for_each(newStuff, chug());
return 0;
};
如何让for_each(newStuff,chug())起作用?
(注意:我只是假设来自boost :: fusion的overly brief documentation我每次调用push_back时都应该创建一个新的向量。)
答案 0 :(得分:1)
(注意:我只是从关于boost :: fusion的过于简短的文档中假设我每次调用push_back时都应该创建一个新的向量。)
您没有创建新的矢量。 push_back
在扩展序列上返回一个延迟评估的view。如果你想创建一个新的矢量,那么例如typedef
NewStuff
为
typedef fusion::vector<Base*, Alpha*, Bravo*, Base*, Alpha*> NewStuff;
你的程序就可以了。
Btw,fusion是一个非常实用的设计。我认为如果你存储实际的对象而不是指针并使用transform
,那将更像融合。然后,chug
逻辑将从类中移出到struct chug
,每个类型都有operator()
个{{1}}。然后,不必创建新的向量,您可以使用延迟评估的视图。