是否存在对象的"this"的类比,但对于函数?

v01*_*dya 9 c++ function-pointers this

我已经搜索了引用和一般网络,但我无法找到,如果它存在.

有没有办法在C++中获取指向当前函数的指针?它是如此微不足道,它应该存在.

在完美的世界中,我想找到一种获得std::function当前函数的方法,但即使是旧式指针也可以.

澄清为什么可能需要它:我正在考虑Lambda函数内部的递归,甚至是函数中的一般递归,在将来的版本中,名称更改的可能性很大.

Luc*_*ore 13

没有,很大程度上是因为没有必要.在(非匿名函数)函数的上下文中,您始终知道自己的位置 - 您始终可以使用其名称来引用它或获取其地址.与对象不同,不同的对象具有不同的地址,因此需要this.


Che*_*Alf 4

一般来说你不能。例如,在可转换为原始函数指针的 lambda 中,没有(标准语言)方法可以在函数内获取该指针。

但是,您可以通过 Macro 获取原始字符串形式的函数名称__func__,但只有最新版本的编译器才为其提供该宏名称。

另外,如果您对不可移植的代码感到满意,那么有几个特定于编译器的自省工具(我只知道它们存在,但必须通过谷歌搜索才能列出它们)。


解决问题新添加的部分,如何让函数递归并仍然支持简单的名称更改和/或 lambda。

一种方法是使用 a std::function,但更简单(并且可能更有效)是将递归函数定义为内部实现细节,例如在命名空间或内部类中:

#include <iostream>
using namespace std;

void foo( int const x )
{
    struct Recursive {
        inline static void foo( int const x )
        {
            cout << x << ' ';
            if( x > 0 ) { foo( x - 1 ); }
        }
    };

    Recursive::foo( x );
    cout << endl;
}

auto main() -> int
{
    foo( 3 );
}
Run Code Online (Sandbox Code Playgroud)

如何使用 lambda 而不是命名函数来执行上述操作:

#include <iostream>
using namespace std;

auto main() -> int
{
    auto const foo = []( int const x ) -> void
    {
        struct Recursive {
            inline static void foo( int const x )
            {
                cout << x << ' ';
                if( x > 0 ) { foo( x - 1 ); }
            }
        };

        Recursive::foo( x );
        cout << endl;
    };

    foo( 3 );
}
Run Code Online (Sandbox Code Playgroud)

  • 出于兴趣,为什么是 `auto main() -&gt; int` 而不是 `void foo( int const x )`?只是踢轮胎,还是不同风格有一些巧妙的暗示? (2认同)