Auto Class Generator

2019-08-21 11:35发布

问题:

I had originally asked this question here: Former Question

It appears that what I was asking for was misunderstood. I will try to make this as clear and as brief as possible:


I'm working on a parser that will automatically generate a c++ class and if the names of the header and cpp files are present the parser will write out those files respectively. If they are omitted then the parser will not write any files where it will generate a class automatically based on the information that is pulled in from the file.

What I don't know how to do: Let's say my class's identifier is stored in a std::string how can I extract the text in the string to use that as the class's name. For example:

{ 
    std::string className( "Foo" );

    // parser writing class in code
    class className { ....

} 

This is what I don't know how to do if it can even be done. As stated in my previous question I prefer to stay away from macros but wouldn't mind using templates if needed or some other mechanism.


Conclusion

After reading the comments and the provided answer below; my initial assumption that I didn't mention was in fact proven true. It can not be done. I was suspicious of this, but only wanted to confirm. So this does leave me in having to write out to files in order to create the needed header and or source files at run time.

回答1:

You can't.

C++ programs cannot modify themselves.

If you want to auto-generate C++ code, do it as an pre-compilation step in your build process.

I myself have a nice Python script generating a ton of C++ classes (and their accompanying boilerplate) each representing one of several "message types" defined by a third party. It's lovely.