简体   繁体   English

将几十个非成员函数转换为方法?

[英]Converting dozens of non-member functions to methods?

Let's say we have some class Foo and we have many non-member functions that mutate vectors of class Foo ; 假设我们有一些class Foo ,我们有很多非成员函数可以改变class Foo向量; ie: 即:

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. 假设我们有许多这样的函数来操纵Foo向量。 So we roll up a class called FooStore that contains a vetor of Foo and has methods to manipulate that Foo vector. 因此,我们推出了一个名为FooStore的类,它包含一个Foo FooStore ,并具有操作Foo向量的方法。

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? 该功能是否仅为非会员?

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. 我可以看到这样做的好处,因为你不想将foos暴露给外面...而且,你不想通过复制/粘贴两次指定“文本”,可能会在前进中犯错误呼叫。

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: 在c ++ 11中,它可以修改如下:

#define FOO_STORE_FWD(name)\
    auto name() -> decltype(::name(&foos)){ return ::name(&foos); }

this should handle forwarding to functions multiple return types 这应该处理多个返回类型的函数转发

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM