Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If you know what are the types the user may input, you can use templates and inheritance:</p> <pre><code>class Generic { public: virtual void process_input() = 0; // Handles the next input from user virtual void process_output() = 0; // Processes the data inserted }; template &lt;typename T&gt; class HandleInput : public Generic { private: std::vector&lt;T&gt; storage; public: HandleInput(T first) { storage.push_back(first); } void process_input() { // do whatever you want } void process_output() { // do whatever you want } }; int main(int argc, char **argv) { // Get first input Input i = input(); Generic *g; // Instantiate the "right" generic with a switch switch (i.type) { case T: g = new HandleInput&lt;T&gt;(i.value); } // Use Generic from here onwards } </code></pre> <p>That's just an idea (<code>Input</code> cannot be implemented like that, you need to change that part with the logic that gets something from the user and determines its type), but it has the benefit of masking the type into a generic class, so you can factor your code around the interface provided by <code>Generic</code>.</p> <p>Another idea (easier, probably) is using a <code>std::vector&lt;void*&gt;</code> and an <code>enum</code> that tells you what the type of the data stored in the vector is. When you need to process that data somewhere in the future, you can switch on the enum to appropriately cast the vector elements to the correct type and dispatch them to the appropriate code.</p> <p><strong>EDIT</strong>: another idea is to define a templatized function that takes the input and sorts the array using standard comparators:</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;algorithm&gt; #include &lt;boost/lexical_cast.hpp&gt; template &lt;typename T&gt; void print_v(std::vector&lt;T&gt; &amp;v) { typename std::vector&lt;T&gt;::iterator it; for (it = v.begin(); it != v.end(); it++) std::cout &lt;&lt; *it &lt;&lt; " "; std::cout &lt;&lt; std::endl; } template &lt;typename T&gt; void sort_and_print(T first, size_t n, bool asc) { std::vector&lt;T&gt; v; v.push_back(first); for (size_t i = 0; i &lt; n; i++) { std::string s; std::cin &gt;&gt; s; T e = boost::lexical_cast&lt;T&gt;(s); v.push_back(e); } print_v(v); if (asc) std::sort(v.begin(), v.end(), std::greater&lt;T&gt;()); else std::sort(v.begin(), v.end()); print_v(v); } int main(int argc, char **argv) { std::string s = "test"; sort_and_print(s, 2, true); unsigned int j = 3; sort_and_print(j, 2, true); return 0; } </code></pre> <p>The logic to determine the type of the first input is up to you (maybe you can open another question) ;)</p>
 

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