gpt4 book ai didi

C++函数链返回函数

转载 作者:行者123 更新时间:2023-11-27 23:37:00 25 4
gpt4 key购买 nike

首先对标题不太清楚感到抱歉,用代码解释它要容易得多:

给定一个这样的函数原型(prototype):

auto sum(int a){
...
}

我希望能够以这种方式使用它:

add(3) == 3 //true
add(1)(2)(3) == 6 //true

我只是为了个人知识而尝试这样做,所以如果有人能指出我应该学习哪些结构来实现这一点,我将不胜感激(我很确定我必须使用 std::function,但我不知道怎么做),而不是给我简单的解决方案。

提前谢谢大家。

最佳答案

可能不是准确答案,但你可以这样试试:

class foo {
int data = 0;
public:
foo& operator()(int i) { data += i; return *this; }
bool operator==(int i) { return this-> data == i; }
void print() const { cout << data << endl; }
};

int main() {

foo add;
add(1)(2)(3);
add.print();
cout << (add(3) == 9 ? "Same" : "Not same") << endl;
}

关于C++函数链返回函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58544561/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com