Black magic C ++

This only needs to work in g ++.

I need a function

template<typename T> std::string magic();

such that:

Class Foo{}; magic<Foo>(); // returns "Foo";
Class Bar{}; magic<Bar>(); // returns "Bar";

I don’t want this to be done using specialization (i.e. to define magic for each type. I hope to get the macro / template black magic here. Does anyone know how?)

Thank!

+5
source share
5 answers

Try typeid(Foo).name()to get started. Disassemble as you see fit; will be implementation dependent (but just wrapping the line is wrapped back).

+7
source

( ) , , , . , ​​ :

template<typename T>
std::string magic_impl(const char *name) { return name; }

#define more_magic(a) magic_impl<a>(#a)
#define magic(a) more_magic(a)

magic(int) "int", magic(Foo) "Foo was not announce", .

+10

, :

#define MAGICCLASSNAME(str) std::string magic(#str)
class Foo{}; MAGICCLASSNAME(foo)
+4

:

#include <iostream>
#include <string>
#include <typeinfo>

using namespace std;
class Foo{}; 
class Bar{};

template<typename T> 
inline std::string magic(const T& obj)
{
 return typeid(obj).name();
}

int main()
{
 Foo a;
 cout << magic<Foo>(a); // returns "Foo";
}

g++ .

SO.

+1

++, , . , Modern ++ Design .

-1

All Articles