簡體   English   中英

使用std :: mem_fun時如何傳遞兩個參數?

[英]How to pass two parameters when using std::mem_fun?

可以說我有這樣的層次結構(這只是一個測試程序。請不要指出與內存泄漏有關的任何內容,析構函數不是虛擬的等等):

class I
{
public:
    virtual void fun(int n, int n1) = 0;
};

class A : public I
{
public:
    void fun(int n, int n1)
    {
        std::cout<<"A::fun():" <<n<<" and n1:" <<n1<<"\n";
    }
};

class B : public I
{
public:
    void fun(int n, int n1)
    {
        std::cout<<"B::fun():" <<n<<" and n1:" <<n1<<"\n";
    }
};


int  main()
{
    std::vector<I*> a;
    a.push_back(new A);
    a.push_back(new B);

    //I want to use std::for_each to call function fun with two arguments.
}

如何調用fun()方法,該方法使用std :: for_each獲取兩個參數? 我想我必須使用std :: mem_fun可能與std :: bind2nd但是我無法弄清楚如何做到這一點。 任何線索如何實現這一目標? 我沒有使用提升。

您可以像這樣創建自己的仿函數:

class Apply
{
private:
  int arg1, arg2;

public:
  Apply(int n, int n1)
    : arg1(n), arg2(n1) 
  {}        

  void operator() (I* pI) const
  {
    pI->fun(arg1, arg2);
  }
};

int main ()
{
  // ...
  std::for_each(a.begin(), a.end(), Apply(n, n1));
}

或者像這樣使用boost :: bind:

std::for_each(
  a.begin(),
  a.end(),
  boost::bind(&I::fun, _1, n, n1));

您無法使用標准粘合劑執行此操作。 你當然可以編寫自己的仿函數。

struct TwoArguments
{
   int one;
   int two;

   TwoArguments( int one, int two ) : one(one),two(two){
   }

   void operator()( I* i ) const {
       i->fun( one, two );
   }
};

另一種方法是使用模板。 (請告訴我這是不好的做法!)

template<int N, int N1>
void Apply(I* i)
{
  i->fun(N, N1);
}

std::for_each(a.begin(), a.end(), Apply<firstParam, secondParam>);

如果你不打算用很多不同的參數調用它,那將是很好的,因為它會為你所做的每個組合生成代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM