通过在函数后写N个括号来调用函数N次

时间:2012-09-02 08:43:41

标签: c++

我想实现以下内容:

我定义了一个函数。当我在函数之后写 N ()时,该函数将被称为 N 次。

我举个例子:

#include <iostream>
using namespace std;

typedef void* (*c)();
typedef c (*b)();
typedef b (*a)();

a aaa()
{
    cout<<"Google"<<endl;

    return (a)aaa;
}

int main()
{
    aaa()()()();
    system("pause");
}

然后输出是:

enter image description here

还有其他方法可以实现吗?

2 个答案:

答案 0 :(得分:6)

使用仿函数很简单。

#include <iostream>

struct Function
{
   Function& operator()() {
      std::cout << "Google" << std::endl;
      return *this;
   }
};

int main()
{
   Function f;
   f()()()();
}

答案 1 :(得分:1)

您可能对仿函数感兴趣:

#include <iostream>

class my_functor {
    public:
    //  if called without parameters
        my_functor& operator()(){
            std::cout << "print" << std::endl;
            return *this;
        }
    //  if called with int parameter
        my_functor& operator()(int number){
            std::cout << number << std::endl;
            return *this;
        }
};

int main(){
    my_functor functor;
    functor()(5)();
    return 0;
}

通过重载函数调用操作符(),可以向对象添加函数行为。您还可以定义不同的参数,这些参数将传递给重载的() - 运算符,并且将调用相应的函数调用。如果要调用上一个函数调用修改过的对象实例上的函数调用,请确保返回对this-instance的引用。

相关问题