// ... 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 时创建一个新 vector 。)
最佳答案
(Note: I'm only assuming from the overly brief documentation on boost::fusion that I am supposed to create a new vector every time I call push_back.)
您不是在创建新 vector 。 push_back
返回延迟计算的 view在扩展序列上。如果你想创建一个新的 vector ,那么例如typedef
NewStuff
作为
typedef fusion::vector<Base*, Alpha*, Bravo*, Base*, Alpha*> NewStuff;
然后你的程序就可以运行了。
顺便说一句, fusion 是一种非常实用的设计。我认为如果您存储实际对象而不是指针并使用 transform
,它会更像 fusion 。然后,chug
逻辑将从类中移出到 struct chug
中,它为每种类型提供了适当的 operator()
。那时不必创建新的 vector ,您可以使用延迟评估的 View 。
关于c++ - boost::fusion::push_back 的正确用法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2841589/