Note that there are some explanatory texts on larger screens.

plurals
  1. POAny suggestion for doing an arbitrary operation using given arguments of arbitrary types?
    primarykey
    data
    text
    <p>Basically i just want to do an arbitrary operation using given arguments of arbitrary types.</p> <p>Argument type base class is Var, and Operation is base class of the operation that will executed for given arguments.</p> <p>I have Evaluator class, that hold a collection of operators which mapped using opId. Evaluator will do operation based on opId argument given in evaluate() member function, then evaluate() function will do search for supported operator that will accept argument type and opId.</p> <p>what I want to ask is, is there any <strong>efficient pattern or algorithm</strong> that will do this <strong>without dynamic_cast&lt;> and/or looping through operator collection</strong>.</p> <p>` </p> <pre><code>class Var { public: bool isValidVar(); static Var invalidVar(); } template&lt;typename T&gt; class VarT : public Var { public: virtual const T getValue() const; } class Operator { public: virtual Var evaluate(const Var&amp; a, const Var&amp; b) = 0; } template&lt;typename T&gt; class AddOperator : public Operator { public: virtual Var evaluate(const Var&amp; a, const Var&amp; b) { //dynamic_cast is slow! const VarT&lt;T&gt;* varA = dynamic_cast&lt;const VarT&lt;T&gt;*&gt;(&amp;a); const VarT&lt;T&gt;* varB = dynamic_cast&lt;const VarT&lt;T&gt;*&gt;(&amp;b); if(varA &amp;&amp; varB) //operation supported { return VarT&lt;T&gt;(varA-&gt;getValue() + varA-&gt;getValue()); } return Var::invalidVar(); //operation for this type is not supported } } class Evaluator { private: std::map&lt;int,std::vector&lt;Operator&gt;&gt; operatorMap; public: virtual Var evaluate(const Var&amp; a, const Var&amp; b,int opId) { std::map&lt;int,std::vector&lt;Operator&gt;&gt;::iterator it = this-&gt;operatorMap.find(opId); if(it != this-&gt;operatorMap.end()) { for(size_t i=0 ; i&lt;it-&gt;second.size() ; i++) { Var result = it-&gt;second.at(i).evaluate(a,b); if(result.isValidVar()) { return result; } } } //no operator mapped, or no operator support the type return Var::invalidVar(); } } </code></pre> <p>`</p>
    singulars
    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.
 

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