函数返回指针本身? [英] Function returning pointer to itself?
本文介绍了函数返回指针本身?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在C ++中是否可以编写一个函数来返回一个指向自己的指针?
Is it possible in C++ to write a function that returns a pointer to itself?
如果没有,建议一些其他解决方案使下面的语法工作: p>
If no, suggest some other solution to make the following syntax work:
some_type f ()
{
static int cnt = 1;
std::cout << cnt++ << std::endl;
}
int main ()
{
f()()()...(); // n calls
}
这必须打印从1到<$ c的所有数字$ c> n 。
推荐答案
struct function
{
function operator () ()
{
//do stuff;
return function();
}
};
int main()
{
function f;
f()()()()()();
}
如果需要,您可以选择返回函数的引用,并返回 * this
;
You can choose to return a reference to function if needed and return *this
;
更新: 对于类型 T
的函数不可能返回 T *
或 T&
Update: Of course, it is syntactically impossible for a function of type T
to return T*
or T&
Update2:
Update2:
当然,如果你想保留你的语法...是
Of course, if you want one to preserve your syntax... that is
some_type f()
{
}
然后这里有一个Idea
Then here's an Idea
struct functor;
functor f();
struct functor
{
functor operator()()
{
return f();
}
};
functor f()
{
return functor();
}
int main()
{
f()()()()();
}
这篇关于函数返回指针本身?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文