C++ boost::fusion::push_back的正确用法是什么? /。。。iostream和fusion的截图包括。。。 名称空间融合=boost::fusion; 阶级基础 { 受保护:int x; public:Base():x(0){} void chug(){ x++; 库特
(注意:我只是从关于boost::fusion的过于简短的文档中假设,每次调用push_back时,我都应该创建一个新的向量。) 您没有创建新向量。C++ boost::fusion::push_back的正确用法是什么? /。。。iostream和fusion的截图包括。。。 名称空间融合=boost::fusion; 阶级基础 { 受保护:int x; public:Base():x(0){} void chug(){ x++; 库特,c++,boost,boost-fusion,C++,Boost,Boost Fusion,(注意:我只是从关于boost::fusion的过于简短的文档中假设,每次调用push_back时,我都应该创建一个新的向量。) 您没有创建新向量。push_-back返回对扩展序列的延迟计算。如果要创建新向量,则例如typedefNewStuffas // ... snipped includes for iostream and fusion ... namespace fusion = boost::fusion; class Base { protected: int x; publi
push_-back
返回对扩展序列的延迟计算。如果要创建新向量,则例如typedef
NewStuff
as
// ... 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;
};
typedef fusion::vector NewStuff;
那你的程序就行了
顺便说一句,fusion是一种功能性很强的设计。我认为它更像是一种fusion,如果你存储实际对象而不是指针,并使用
transform
。然后chug
逻辑将从类中移到struct chug
中,它具有适当的操作符()
,适用于每种类型。无需创建新的向量,您可以使用惰性评估的视图。非常有用,谢谢。切换到实际对象会有什么好处,尤其是在它们不可复制的情况下?(不确定fusion是否复制)。至少,它简化了内存管理(无需在某个地方显式删除,异常安全),并且不必担心可能的空指针(除非某些值是可选的)。
typedef fusion::vector<Base*, Alpha*, Bravo*, Base*, Alpha*> NewStuff;