tags:

views:

256

answers:

5

__FILE__ and __LINE__ are well known. There is a __func__ since C99.

#include <iostream>
struct Foo {
        void Do(){ std::cout << __func__ << std::endl; }
};

int main()
{
        std::cout << __func__ << std::endl;
        Foo foo; foo.Do();
        return 0;
}

will output

main
Do

Is there any macro / keyword that would output method name like Foo::Do?

A: 

Not in Standard C++ (and __func__ is not part of C++). Your implementation may have such a feature though - which compiler are you using?

anon
I'm interested in g++ and MSVC++ too.
Notinlist
+1  A: 

See "Predefined Macros (C/C++)" for a complete list supported by MS Visual Studio.

Ruddy
+3  A: 
  • On GCC you can use __FUNCTION__ and __PRETTY_FUNCTION__.
  • On MSVC you can use __FUNCSIG__ and __FUNCTION__.
rpg
`__PRETTY_FUNCTION__` is awesome! Will test `__FUNCSIG__` later.
Notinlist
+2  A: 

There's no such macro in standard C++, and that includes the draft C++0x standard I looked at. It would complicate compilation, since parsing (necessary to determine what a function is) comes after preprocessing, and I suspect that's why there's nothing in the standard.

The __func__ you're using is nonstandard, although it apparently works on your compiler.

David Thornley
+9  A: 

Boost has a special utility macro called BOOST_CURRENT_FUNCTION that hides the differences between the compiler implementations.

Following it's implementation we see that there are several macros depending on compiler:

  • __PRETTY_FUNCTION__ -- GCC, MetroWerks, Digital Mars and ICC
  • __FUNCSIG__ -- MSVC
  • __FUNCTION__ -- Intel and IBM
  • __FUNC__ -- Borland
  • __func__ -- ANSI C99
Kornel Kisielewicz
+1 for presenting a solution that works on multiple platforms
Matthieu M.
@Matthieu, thank Boost for that :)
Kornel Kisielewicz
+1. This is an excellent solution. I hadn't discovered this yet.
Fred Larson
@Kornel: the problem with Boost is that often times it has solutions for things you did not even thought about. I did not think it was "possible" and therefore I did not try to look it up...
Matthieu M.