0

Assume I have:

#include <iostream>
class Greeter
{
public:
    void printEm() {...}
private:
    std::string a = "Hello!";
    std::string b = "Hi!";
    int IAmNotAString = 0;
};

What is the simplest way to get printEm to print all the defined strings in Greeter, and further, should someone define a new string, print that one too? Any boost library is fine - I have some experience with Fusion, but I don't know how it could automatically infer which members are strings.

Carbon
  • 3,828
  • 3
  • 24
  • 51
  • I don't think I understand, do you have only 2 strings in class ? How is someone supposed to add new string to current class? I think you need an array or list. Then it is easy to print all of them, only iterate through array, list, and adding is solved. – Angen Dec 20 '17 at 21:33
  • Imagine 50 strings, and they're actually functions. And developers add and remove them. And there's a monstrous macro that handles this monstrosity automatically. – Carbon Dec 20 '17 at 21:35
  • So it goes, such is life. – Carbon Dec 20 '17 at 21:36
  • 1
    maybe take look here https://stackoverflow.com/questions/19059157/iterate-through-struct-and-class-members – Angen Dec 20 '17 at 21:40
  • 1
    strings are actually functions, what? – juanchopanza Dec 20 '17 at 21:41
  • 1
    C++ doesn't have reflection at this level. There are solutions (custom string class, external code generator, ...), but your question is quite vague. Try creating MCVE, and explaining any constraints. – hyde Dec 20 '17 at 21:43
  • There are bigger and better fishes to fry in C++. Avoid macros. Prefer templates. – Ron Dec 20 '17 at 21:59
  • @Carbon Dynamic data should be in data structures like vectors or maps, not separate variables. Your design seems fundamentally flawed if you need to be able to iterate through all the strings. – Barmar Dec 20 '17 at 22:27
  • I do not disagree, it's hard weaning people from what they're used to. – Carbon Dec 20 '17 at 22:44

1 Answers1

1

C++ does not have any reflection. If you want to do this with macros, you would also have to define your member variables using specially crafted macros. A simple idea would be each macro would add the member to am internal vector and your printEm would just iterate through this vector. It's not the most elegant solution but it's how various libraries work.

Eyal Cinamon
  • 939
  • 5
  • 16