Risposte:
La cosa più vicina che c'è da chiamare typeid(your_class).name(), ma questo produce un nome alterato specifico del compilatore.
Per usarlo solo in classe typeid(*this).name()
__func__e non standard __FUNCTION__non sono macro. Microsoft documenta __FUNCTION__come macro, ma il giveaway che non lo è realmente, è che non viene espanso dal preprocessore quando si compila con /P.
Il problema con l'utilizzo typeid(*this).name()è che non vi è alcun thispuntatore in una chiamata al metodo statico. La macro __PRETTY_FUNCTION__riporta un nome di classe nelle funzioni statiche e nelle chiamate al metodo. Tuttavia, questo funzionerà solo con gcc.
Ecco un esempio di estrazione delle informazioni tramite un'interfaccia in stile macro.
inline std::string methodName(const std::string& prettyFunction)
{
size_t colons = prettyFunction.find("::");
size_t begin = prettyFunction.substr(0,colons).rfind(" ") + 1;
size_t end = prettyFunction.rfind("(") - begin;
return prettyFunction.substr(begin,end) + "()";
}
#define __METHOD_NAME__ methodName(__PRETTY_FUNCTION__)
La macro __METHOD_NAME__restituirà una stringa del modulo <class>::<method>(), tagliando il tipo di ritorno, i modificatori e gli argomenti da ciò che __PRETTY_FUNCTION__ti dà.
Per qualcosa che estrae solo il nome della classe, è necessario prestare attenzione a intercettare situazioni in cui non esiste una classe:
inline std::string className(const std::string& prettyFunction)
{
size_t colons = prettyFunction.find("::");
if (colons == std::string::npos)
return "::";
size_t begin = prettyFunction.substr(0,colons).rfind(" ") + 1;
size_t end = colons - begin;
return prettyFunction.substr(begin,end);
}
#define __CLASS_NAME__ className(__PRETTY_FUNCTION__)
#ifdef __GNU_C__?
substr(0,colons).rfind(" ")uno potrebbe usare rfind(' ', colons)per risparmiare la creazione di una stringa extra.
constexprfunzione per valutarlo in fase di compilazione
Vorrei suggerire boost :: typeindex , che ho imparato da "Effective Modern C ++" di Scott Meyer. Ecco un esempio di base:
Esempio
#include <boost/type_index.hpp>
class foo_bar
{
int whatever;
};
namespace bti = boost::typeindex;
template <typename T>
void from_type(T t)
{
std::cout << "\tT = " << bti::type_id_with_cvr<T>().pretty_name() << "\n";
}
int main()
{
std::cout << "If you want to print a template type, that's easy.\n";
from_type(1.0);
std::cout << "To get it from an object instance, just use decltype:\n";
foo_bar fb;
std::cout << "\tfb's type is : "
<< bti::type_id_with_cvr<decltype(fb)>().pretty_name() << "\n";
}
Compilato con "g ++ --std = c ++ 14" produce quanto segue
Produzione
Se vuoi stampare un tipo di modello, è facile.
T = doppio
Per ottenerlo da un'istanza di oggetto, usa semplicemente decltype:
Il tipo di fb è: foo_bar
Non ancora. (Penso __class__sia proposto da qualche parte). Puoi anche provare a estrarre la parte della classe da __PRETTY_FUNCTION__.
Se hai bisogno di qualcosa che produca effettivamente il nome della classe in fase di compilazione, puoi usare C ++ 11 per farlo:
#define __CLASS__ std::remove_reference<decltype(classMacroImpl(this))>::type
template<class T> T& classMacroImpl(const T* t);
Riconosco che questa non è la stessa cosa __FUNCTION__ma ho trovato questo post mentre cercavo una risposta come questa. : D
Se stai parlando di MS C ++ (dovresti indicare, specialmente perché __FUNCTION__è un'estensione non standard), ci sono __FUNCDNAME__e __FUNCSIG__simboli che potresti analizzare
È possibile ottenere il nome della funzione incluso il nome della classe. Questo può elaborare funzioni di tipo C.
static std::string methodName(const std::string& prettyFunction)
{
size_t begin,end;
end = prettyFunction.find("(");
begin = prettyFunction.substr(0,end).rfind(" ") + 1;
end -= begin;
return prettyFunction.substr(begin,end) + "()";
}
La mia soluzione:
std::string getClassName(const char* fullFuncName)
{
std::string fullFuncNameStr(fullFuncName);
size_t pos = fullFuncNameStr.find_last_of("::");
if (pos == std::string::npos)
{
return "";
}
return fullFuncNameStr.substr(0, pos-1);
}
#define __CLASS__ getClassName(__FUNCTION__)
Lavoro per Visual C ++ 12.
Ecco una soluzione basata sulla __FUNCTION__macro e sui modelli C ++:
template <class T>
class ClassName
{
public:
static std::string Get()
{
// Get function name, which is "ClassName<class T>::Get"
// The template parameter 'T' is the class name we're looking for
std::string name = __FUNCTION__;
// Remove "ClassName<class " ("<class " is 7 characters long)
size_t pos = name.find_first_of('<');
if (pos != std::string::npos)
name = name.substr(pos + 7);
// Remove ">::Get"
pos = name.find_last_of('>');
if (pos != std::string::npos)
name = name.substr(0, pos);
return name;
}
};
template <class T>
std::string GetClassName(const T* _this = NULL)
{
return ClassName<T>::Get();
}
Ecco un esempio di come potrebbe essere usato per una classe logger
template <class T>
class Logger
{
public:
void Log(int value)
{
std::cout << GetClassName<T>() << ": " << value << std::endl;
std::cout << GetClassName(this) << ": " << value << std::endl;
}
};
class Example : protected Logger<Example>
{
public:
void Run()
{
Log(0);
}
}
L'output di Example::Runsarà quindi
Example: 0
Logger<Example>: 0
Funziona abbastanza bene se sei disposto a pagare il costo di un puntatore.
class State
{
public:
State( const char* const stateName ) :mStateName( stateName ) {};
const char* const GetName( void ) { return mStateName; }
private:
const char * const mStateName;
};
class ClientStateConnected
: public State
{
public:
ClientStateConnected( void ) : State( __FUNCTION__ ) {};
};
Funziona anche con msvc e gcc
#ifdef _MSC_VER
#define __class_func__ __FUNCTION__
#endif
#ifdef __GNUG__
#include <cxxabi.h>
#include <execinfo.h>
char *class_func(const char *c, const char *f)
{
int status;
static char buff[100];
char *demangled = abi::__cxa_demangle(c, NULL, NULL, &status);
snprintf(buff, sizeof(buff), "%s::%s", demangled, f);
free(demangled);
return buff;
}
#define __class_func__ class_func(typeid(*this).name(), __func__)
#endif
Tutte le soluzioni pubblicate sopra che si basano su __PRETTY_FUNCTION__hanno casi limite specifici in cui non restituiscono solo il nome della classe / nome della classe. Ad esempio, considera il seguente grazioso valore della funzione:
static std::string PrettyFunctionHelper::Test::testMacro(std::string)
L'uso dell'ultima occorrenza di "::"as delimter non funzionerà poiché il parametro della funzione contiene anche un "::"( std::string). Puoi trovare casi limite simili per "("come delimitatore e altro ancora. L'unica soluzione che ho trovato prende sia la __FUNCTION__e __PRETTY_FUNCTION__macro come parametri. Ecco il codice completo:
namespace PrettyFunctionHelper{
static constexpr const auto UNKNOWN_CLASS_NAME="UnknownClassName";
/**
* @param prettyFunction as obtained by the macro __PRETTY_FUNCTION__
* @return a string containing the class name at the end, optionally prefixed by the namespace(s).
* Example return values: "MyNamespace1::MyNamespace2::MyClassName","MyNamespace1::MyClassName" "MyClassName"
*/
static std::string namespaceAndClassName(const std::string& function,const std::string& prettyFunction){
//AndroidLogger(ANDROID_LOG_DEBUG,"NoT")<<prettyFunction;
// Here I assume that the 'function name' does not appear multiple times. The opposite is highly unlikely
const size_t len1=prettyFunction.find(function);
if(len1 == std::string::npos)return UNKNOWN_CLASS_NAME;
// The substring of len-2 contains the function return type and the "namespaceAndClass" area
const std::string returnTypeAndNamespaceAndClassName=prettyFunction.substr(0,len1-2);
// find the last empty space in the substring. The values until the first empty space are the function return type
// for example "void ","std::optional<std::string> ", "static std::string "
// See how the 3rd example return type also contains a " ".
// However, it is guaranteed that the area NamespaceAndClassName does not contain an empty space
const size_t begin1 = returnTypeAndNamespaceAndClassName.rfind(" ");
if(begin1 == std::string::npos)return UNKNOWN_CLASS_NAME;
const std::string namespaceAndClassName=returnTypeAndNamespaceAndClassName.substr(begin1+1);
return namespaceAndClassName;
}
/**
* @param namespaceAndClassName value obtained by namespaceAndClassName()
* @return the class name only (without namespace prefix if existing)
*/
static std::string className(const std::string& namespaceAndClassName){
const size_t end=namespaceAndClassName.rfind("::");
if(end!=std::string::npos){
return namespaceAndClassName.substr(end+2);
}
return namespaceAndClassName;
}
class Test{
public:
static std::string testMacro(std::string exampleParam=""){
const auto namespaceAndClassName=PrettyFunctionHelper::namespaceAndClassName(__FUNCTION__,__PRETTY_FUNCTION__);
//AndroidLogger(ANDROID_LOG_DEBUG,"NoT2")<<namespaceAndClassName;
assert(namespaceAndClassName.compare("PrettyFunctionHelper::Test") == 0);
const auto className=PrettyFunctionHelper::className(namespaceAndClassName);
//AndroidLogger(ANDROID_LOG_DEBUG,"NoT2")<<className;
assert(className.compare("Test") == 0);
return "";
}
};
}
#ifndef __CLASS_NAME__
#define __CLASS_NAME__ PrettyFunctionHelper::namespaceAndClassName(__FUNCTION__,__PRETTY_FUNCTION__)
#endif
Il seguente metodo (basato su methodName () sopra) può anche gestire input come "int main (int argc, char ** argv)":
string getMethodName(const string& prettyFunction)
{
size_t end = prettyFunction.find("(") - 1;
size_t begin = prettyFunction.substr(0, end).rfind(" ") + 1;
return prettyFunction.substr(begin, end - begin + 1) + "()";
}