Recursively call a function object

孤人 提交于 2020-02-01 20:19:04

问题


How do I call a function object from within itself? Seems I cannot use this. Example:

class factorial {
  public:
  int operator()(int n) {
    if (n == 0)
      return 1;
    return n * ??(n-1);
  }
};

What do I place at ???


回答1:


#include <iostream>

class factorial {
public:
  int operator()(int n) {
    if (n == 0)
      return 1;
    return n * (*this)(n-1);
  }
};

int main()
{
    std::cout << factorial()(5) << std::endl;
}

Works fine for me. Live example.




回答2:


You can either use the name of the overloaded operator:

operator()(n-1);

or invoke the operator on the current object:

(*this)(n-1);



回答3:


As DyP mentioned, you can call (*this)(n-1). However, it's odd to read, so you'd be better off splitting it out into a seperate calculate_factoral method and calling that instead




回答4:


As several people have pointed out you can just use the (*this)(n - 1) syntax. But this syntax isn't exactly intuitive and a slightly better solution may be to factor out the actual implementation into another named method.

class factorial { 
public:
  int operator()(int n) {
    return impl(n);
  }
private:
  int impl(int n) { 
    // actual work here 
  }
};



回答5:


You can either use explicit operator syntax:

class factorial {
  int operator()(int n) {
    if (n == 0)
      return 1;
    return n * operator()(n-1);
  }
};

Or dereference this:

class factorial {
  int operator()(int n) {
    if (n == 0)
      return 1;
    return n * (*this)(n-1);
  }
};



回答6:


factorial surely?

I only know Java and a recursive factorial can be written as:

public class Factorial{

    public int factorial(int n) {
        return (n > 1) ? n * factorial(n-1) : 1;
    }
}

I assume the same principle applies.



来源:https://stackoverflow.com/questions/17928321/recursively-call-a-function-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!