开发者

C++ cycling through operators

I have a sum, for example:

x + y

I also want to perform subtraction, multiplication and division on the same two variables:

x - y
x * y
x / y 

what's the optimum way开发者_高级运维 of cycling through all four operators in turn?

I know this is easy to do in functional programming languages but in C++ I'm not sure.

Thanks in advance.


Just one idea besides the obvious "writing them out":

int add(int l, int r){
  return l + r;
}

int sub(int l, int r){
  return l - r;
}

int mul(int l, int r){
  return l * r;
}

int div(int l, int r){
  return l / r;
}

int main(){
  typedef int (*op)(int,int);
  op ops[4] = {add, sub, mul, div};

  int a = 10, b = 5;
  for(int i=0; i < 4; ++i){
    ops[i](a,b);
  }
}

Example at Ideone.


If the operators are user defined, they may be passed when pointer to functions (members) are expected. For basic types, you may need to write wrappers as Xeo showed.

You can also accept a std::binary_function and use std::plus and so on.

This is made easier in C++0X with std::function and lambda.

But obviously, knowing more precisely what you want to achieve would help.


Probably this is how it could looks like (similar to functional programming languages):

template<typename T>
std::vector<T> do_ops( const T& a, const T& b )
{
  std::vector<T> result;
  result.push_back( a + b );
  result.push_back( a - b );
  result.push_back( a * b );
  result.push_back( a / b );
  return result;
}

int main()
{
  std::vector<int> res = do_ops( 10, 5 );  
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜