Note that there are some explanatory texts on larger screens.

plurals
  1. POhow to do function pointer like in C++, but for variable
    primarykey
    data
    text
    <p>sorry for the title, it's quite confusing to explain, but it will be more clear with example</p> <p>In C, I used to write program like this :</p> <pre><code>void createClassA() { } void createClassB() { } typedef struct { const char *name; void (*create_class)(); } MapList; MapList mapList[] = { {"A", &amp;createClassA}, {"B", &amp;createClassB }, }; void create(const char *name) { int i=0; for (i=0; i &lt; sizeof(mapList) / sizeof(MapList); i++) { if (strcmp(name, mapList[i].name) == 0) mapList[i].create_class(); } } int main(int argc, char** argv) { if (argc &lt; 1) return -1; create(argv[1]); return 0; } </code></pre> <p>So if I have more types, all I have to do is to create the function itself and add it to the mapList.</p> <p>but in C++, the best I can do is something like:</p> <pre><code>#include &lt;iostream&gt; class myA{}; class myB{}; class myC{}; class Base { public: template&lt;class T&gt; void createClass() { T* t = new T(); //t-&gt;doSomethingUseful(); } void create(const std::string name) { if (name=="A") createClass&lt;myA&gt;(); else if (name=="B") createClass&lt;myB&gt;(); else if (name=="C") createClass&lt;myC&gt;(); } }; int main(int agrc, char** argv) { if (argc&lt;1) return -1; Base b; b.create(argv[0]); return 0; } </code></pre> <p>Can I create something like :</p> <pre><code>typedef struct { std::string name; [CLASS_TYPE] class_type; &lt;== I don't know how } MapList; </code></pre> <p>so I can create a mapping List but fill it with class Type, something like</p> <pre><code>mapList[] = { {"A", myA}, {"B", myB}, {"B", myC}, }; </code></pre> <p>and then I can create iteration like:</p> <pre><code>for (int i=0; i&lt;sizeof(mapList) / sizeof(MapList); i++) { if (mapList[i].name == name) b.createClass&lt;mapList[i].classType&gt;(); } </code></pre> <p>Thanks guys :)</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload