假设我们有一些class Foo并且我们有很多非成员函数可以改变class Foo向量; 即:
void remove_duplicate_foos(std::vector<Foo>* foos_io) { std::vector<Foo>& foos = &foos_io; // removing duplicates }假设我们有许多这样的函数可以操纵Foo向量。 所以我们推出了一个名为FooStore的类,它包含一个Foo FooStore ,并且有操作Foo向量的方法。
class FooStore { public: void remove_duplicates() { ::remove_duplicates(&foos); } private: std::vector<Foo> foos; }现在,有几十种方便的方法吗? 这是一个坏主意吗? 该功能是否仅为非会员?
Let's say we have some class Foo and we have many non-member functions that mutate vectors of class Foo; i.e:
void remove_duplicate_foos(std::vector<Foo>* foos_io) { std::vector<Foo>& foos = &foos_io; // removing duplicates }Let's say we have dozens of functions like this that manipulate Foo vectors. So we roll up a class called FooStore that contains a vetor of Foo and has methods to manipulate that Foo vector.
class FooStore { public: void remove_duplicates() { ::remove_duplicates(&foos); } private: std::vector<Foo> foos; }Now, is there any handy way to do pretty much this dozens of times? Is it a bad idea to this? Should the function remain non-member only?
最满意答案
我可以看到这样做的好处,因为你不想将foos暴露给外面...而且,你不想通过复制/粘贴两次指定“文本”,可能在前进中犯了一个错误呼叫。
这或多或少使用宏来解决它:
#include <vector> class Foo{}; void x1(std::vector<Foo>*){} void x2(std::vector<Foo>*){} void x3(std::vector<Foo>*){} class FooStore { public: #define FOO_STORE_FWD(name)\ void name()\ {\ ::name(&foos);\ } FOO_STORE_FWD(x1) FOO_STORE_FWD(x2) FOO_STORE_FWD(x3) #undef FOO_STORE_FWD private: std::vector<Foo> foos; }; void testFooStore() { FooStore f; f.x1(); f.x2(); f.x3(); }此外,我可以看到使一个函数成为朋友的好处,但是那个函数必须“知道”你。 在这种情况下,它知道你的成员,而不是你...
在c ++ 11中,它可以修改如下:
#define FOO_STORE_FWD(name)\ auto name() -> decltype(::name(&foos)){ return ::name(&foos); }这应该处理多个返回类型的函数转发
I can see the benefit of doing this, as you don't want to expose foos to the outside... Also, you don't want to specify the "text" twice by copying/pasting, potentially making a mistake in the forward call.
This more or less solves it using macros:
#include <vector> class Foo{}; void x1(std::vector<Foo>*){} void x2(std::vector<Foo>*){} void x3(std::vector<Foo>*){} class FooStore { public: #define FOO_STORE_FWD(name)\ void name()\ {\ ::name(&foos);\ } FOO_STORE_FWD(x1) FOO_STORE_FWD(x2) FOO_STORE_FWD(x3) #undef FOO_STORE_FWD private: std::vector<Foo> foos; }; void testFooStore() { FooStore f; f.x1(); f.x2(); f.x3(); }Furthermore, I can see the benefit of making a function a friend, but then that function has to "know" about you. In this case it knows about your member, not of you...
In c++ 11, it can be modified as follows:
#define FOO_STORE_FWD(name)\ auto name() -> decltype(::name(&foos)){ return ::name(&foos); }this should handle forwarding to functions multiple return types
更多推荐
发布评论