有没有办法在 C++ 函数中获取函数名? [英] Is there a way to get function name inside a C++ function?

查看:51
本文介绍了有没有办法在 C++ 函数中获取函数名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想实现一个函数跟踪器,它会跟踪一个函数执行的时间.我有以下相同的课程:-

I want to implement a function tracer, which would trace how much time a function is taking to execute. I have following class for the same:-

class FuncTracer
{
    public:
        FuncTracer(LPCTSTR strFuncName_in)
        {
            m_strFuncName[0] = _T('');
            if( strFuncName_in ||
                _T('') != strFuncName_in[0])
            {   
                _tcscpy(m_strFuncName,strFuncName_in);

                TCHAR strLog[MAX_PATH];
                _stprintf(strLog,_T("Entering Func:- <%s>"),m_strFuncName);
                LOG(strLog)

                m_dwEnterTime = GetTickCount();
            }
        }

        ~FuncTracer()
        {
            TCHAR strLog[MAX_PATH];
            _stprintf(strLog,_T("Leaving Func:- <%s>, Time inside the func <%d> ms"),m_strFuncName, GetTickCount()-m_dwEnterTime);
            LOG(strLog)
        }

    private:
        TCHAR m_strFuncName[MAX_PATH];
        DWORD m_dwEnterTime;
};

void TestClass::TestFunction()
{
    // I want to avoid writing the function name maually..
    // Is there any macro (__LINE__)or some other way to 
    // get the function name inside a function ??

    FuncTracer(_T("TestClass::TestFunction"));
    /*
     * Rest of the function code.
     */
}

我想知道是否有任何方法可以从函数内部获取函数的名称?基本上我希望我班级的用户简单地创建一个相同的对象.他们可能不会传递函数名.

I want to know if there is any way to get the name of the function from inside of a function? Basically I want the users of my class to simply create an object the same. They may not pass the function name.

推荐答案

VC++有

__FUNCTION__ for undecorated names

__FUNCDNAME__ for decorated names

你可以编写一个宏,它自己会分配一个对象,并在构造函数中传递名称转换宏.有点喜欢

And you can write a macro that will itself allocate an object and pass the name-yelding macro inside the constructor. Smth like

#define ALLOC_LOGGER FuncTracer ____tracer( __FUNCTION__ );

这篇关于有没有办法在 C++ 函数中获取函数名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆