-2

I would like a way to get a string from a class at compile time, but would also want an error if that class doesn't exist in the scope, so this is not enough:

#define CLASS_STR(c) # c

I guess I could write a post build script as a static analyzer of some sort.

An example would be keypath checking in libextobjc http://devetc.org/code/2014/05/17/safe-and-sane-key-paths.html

It should be simple to grasp, really. Instead of writing "MyClass", one should utilize a macro that can return the class name in a string, while also making sure that class is visible in the scope.

Mazyod
  • 22,319
  • 10
  • 92
  • 157
  • Are you trying to get a `std::string`? AFAIK they are not created until runtime. – NathanOliver Jul 06 '15 at 23:54
  • @NathanOliver just a const string, "MyClass". – Mazyod Jul 06 '15 at 23:57
  • It's not clear what you're asking for. Could you perhaps spend more than twenty seconds writing your question? Thanks. – Lightness Races in Orbit Jul 07 '15 at 00:07
  • It's a very simple concept, not everything needs an encyclopedia written about it to explain it. – Mazyod Jul 07 '15 at 00:13
  • This is possible at runtime: http://stackoverflow.com/questions/1024648/retrieving-a-c-class-name-programatically I am not sure how to do this at compile time. What exactly are you trying to do? – rlbond Jul 07 '15 at 00:16
  • @rlbond trying to create a map between a type and a pointer (to some object factory). So, I thought I could generate the strings from different types at compile time. – Mazyod Jul 07 '15 at 00:25

1 Answers1

0

Here is one way to do it:

#include <iostream>
#include <MyLib/MyClass.h>

#define CLASS_STR(__class__) \
({              \
    __class__ *x;\
    #__class__ ;\
})

int main(int argc, char* argv[]) {

    auto className = CLASS_STR(MyClass);

    std::cout << className << std::endl;

    return 0;
}

Notice if I passed in MyKlass to the macro, it will fail to initialize the pointer, so now I have a compile time check that the class is available. After the check, I get a string, which is guaranteed to represent that class.

Of course, one can easily redefine the macro for release builds to just perform the stringification.

Mazyod
  • 22,319
  • 10
  • 92
  • 157