Esiste una macro __CLASS__ in C ++?


100

C'è una __CLASS__macro in C ++ che dà il nome della classe simile alla __FUNCTION__macro che dà il nome della funzione

Risposte:


67

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()


2
typeid (* this) .name () può essere utilizzato all'interno delle funzioni di classe
Aleksei Potov

2
Così va meglio. Per quanto riguarda la conoscenza della classe, definire l'array di caratteri è meglio che rimandarlo a runtime.
Michael Krelin - hacker

5
È un peccato che non sia definito come __ CLASS __, può essere utile nella fase di preprocessore! :(
k3a

2
@ Max Non lo fa ma potrebbe.
Allo

5
@kexik: neanche il preprocessore conosce le funzioni, standard __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.
Steve Jessop

77

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__)

5
Non dovresti circondarlo #ifdef __GNU_C__?
einpoklum

1
invece di substr(0,colons).rfind(" ")uno potrebbe usare rfind(' ', colons)per risparmiare la creazione di una stringa extra.
mariusm

1
Preferisco usare find_last_of ("::") Altrimenti la funzione restituirà solo uno spazio dei nomi se ce n'è uno
underdoeg

Ho scritto una versione possibilmente più ampia della __METHOD_NAME__macro. Controlla qui .
Antonio

In C ++ 11 potresti provare a renderlo una constexprfunzione per valutarlo in fase di compilazione
Andre Holzner,

11

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


È possibile ottenere solo il nome della classe senza spazi dei nomi con questo? aka coliru.stacked-crooked.com/a/cf1b1a865bb7ecc7
tower120

9

Non ancora. (Penso __class__sia proposto da qualche parte). Puoi anche provare a estrarre la parte della classe da __PRETTY_FUNCTION__.


7

Penso che l'uso __PRETTY_FUNCTION__sia abbastanza buono sebbene includa anche lo spazio dei nomi, cioè namespace::classname::functionnamefino a quando non __CLASS__è disponibile.


4

Se il tuo compilatore è g++e lo stai chiedendo __CLASS__perché vuoi un modo per ottenere il nome del metodo corrente inclusa la classe, __PRETTY_FUNCTION__dovrebbe aiutare (secondo la info gccsezione 5.43 Nomi di funzioni come stringhe ).


3

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



2

È 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) + "()";
}

1

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.


1

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

Nota che questo non terrà in considerazione il polimorfismo se hai un puntatore alla base (che probabilmente va bene).
Gare di leggerezza in orbita

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__ ) {};
};

0

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

0

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

-2

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) + "()";
}
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.