Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 650603
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 13, 20262026-05-13T22:04:16+00:00 2026-05-13T22:04:16+00:00

Basically i just want to do an arbitrary operation using given arguments of arbitrary

  • 0

Basically i just want to do an arbitrary operation using given arguments of arbitrary types.

Argument type base class is Var, and Operation is base class of the operation that will executed for given arguments.

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.

what I want to ask is, is there any efficient pattern or algorithm that will do this without dynamic_cast<> and/or looping through operator collection.

`

class Var {
public:
    bool isValidVar();
    static Var invalidVar();
}

template<typename T> class VarT : public Var {
public:
    virtual const T getValue() const;   
}

class Operator {
public:
    virtual Var evaluate(const Var& a, const Var& b) = 0;
}

template<typename T> class AddOperator : public Operator {
public:
    virtual Var evaluate(const Var& a, const Var& b)
    {                             //dynamic_cast is slow!
        const VarT<T>* varA = dynamic_cast<const VarT<T>*>(&a);
        const VarT<T>* varB = dynamic_cast<const VarT<T>*>(&b);
        if(varA && varB)          //operation supported
        {
            return VarT<T>(varA->getValue() + varA->getValue());
        }
        return Var::invalidVar(); //operation for this type is not supported
    }
}

class Evaluator {
private:
    std::map<int,std::vector<Operator>> operatorMap;
public:
    virtual Var evaluate(const Var& a, const Var& b,int opId)
    {
        std::map<int,std::vector<Operator>>::iterator it = this->operatorMap.find(opId);
        if(it != this->operatorMap.end())
        {
            for(size_t i=0 ; i<it->second.size() ; i++)
            {
                Var result = it->second.at(i).evaluate(a,b);
                if(result.isValidVar())
                {
                    return result;
                }
            }
        }
        //no operator mapped, or no operator support the type
        return Var::invalidVar();
    }
}

`

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-13T22:04:17+00:00Added an answer on May 13, 2026 at 10:04 pm

    if you do not want to use dynamic_cast, consider adding type traits into your design.

    Added 05/03/10 : The following sample will demonstrate how runtime-traits works

    CommonHeader.h

    #ifndef GENERIC_HEADER_INCLUDED
    #define GENERIC_HEADER_INCLUDED
    
    #include <map>
    #include <vector>
    #include <iostream>
    
    // Default template
    template <class T>
    struct type_traits
    {
        static const int typeId = 0;
        static const int getId() { return typeId; }
    };
    
    class Var 
    {
    public:
        virtual ~Var() {}
        virtual int     getType() const = 0;
        virtual void    print() const = 0;
    };
    
    template<typename T> 
    class VarT  : public Var
    {
        T value;
    public:
        VarT(const T& v): value(v) {}
        virtual int     getType() const { return type_traits<T>::getId();   };
        virtual void    print() const { std::cout << value << std::endl;    };
        const T& getValue() const { return value; }
    };
    
    class Operator 
    {
    public:
        virtual ~Operator() {}
        virtual Var* evaluate(const Var& a, const Var& b) const = 0;
    };
    
    template<typename T> 
    class AddOperator : public Operator
    {
    public:
    
        virtual Var* evaluate(const Var& a, const Var& b) const
        {   
            // Very basic condition guarding
            // Allow operation within similar type only
            // else have to create additional compatibility checker 
            // ie. AddOperator<Matrix> for Matrix & int
            // it will also requires complicated value retrieving mechanism
            // as static_cast no longer can be used due to unknown type.
            if ( (a.getType() == b.getType())                   &&
                 (a.getType() == type_traits<T>::getId())       &&
                 (b.getType() != type_traits<void>::getId())  )
            {
                const VarT<T>* varA = static_cast<const VarT<T>*>(&a);
                const VarT<T>* varB = static_cast<const VarT<T>*>(&b);
    
                return new VarT<T>(varA->getValue() + varB->getValue());
            }
            return 0;
        }
    };
    
    
    class Evaluator {
    private:
        std::map<int, std::vector<Operator*>> operatorMap;
    public:
        void registerOperator(Operator* pOperator, int iCategory)
        {
            operatorMap[iCategory].push_back( pOperator );
        }
    
        virtual Var* evaluate(const Var& a, const Var& b, int opId)
        {
            Var* pResult = 0;
            std::vector<Operator*>& opList = operatorMap.find(opId)->second;
            for (   std::vector<Operator*>::const_iterator opIter = opList.begin();
                    opIter != opList.end();
                    opIter++    )
            {
                pResult = (*opIter)->evaluate( a, b );
                if (pResult)
                    break;
            }
    
            return pResult;
        }
    };
    
    #endif
    

    DataProvider header

    #ifdef OBJECTA_EXPORTS
    #define OBJECTA_API __declspec(dllexport)
    #else
    #define OBJECTA_API __declspec(dllimport)
    #endif
    
    // This is the "common" header
    #include "CommonHeader.h"
    
    class CFraction 
    {
    public:
        CFraction(void);
        CFraction(int iNum, int iDenom);
        CFraction(const CFraction& src);
    
        int m_iNum;
        int m_iDenom;
    };
    
    extern "C" OBJECTA_API Operator*    createOperator();
    extern "C" OBJECTA_API Var*         createVar();
    

    DataProvider implementation

    #include "Fraction.h"
    
    // user-type specialization
    template<>
    struct type_traits<CFraction>
    {
        static const int typeId = 10;
        static const int getId() { return typeId; }
    };
    
    std::ostream&   operator<<(std::ostream& os, const CFraction& data)
    {
        return os << "Numerator : " << data.m_iNum << " @ Denominator : " << data.m_iDenom << std::endl;
    }
    
    CFraction   operator+(const CFraction& lhs, const CFraction& rhs)
    {
        CFraction   obj;
        obj.m_iNum = (lhs.m_iNum * rhs.m_iDenom) + (rhs.m_iNum * lhs.m_iDenom);
        obj.m_iDenom = lhs.m_iDenom * rhs.m_iDenom;
        return obj;
    }
    
    OBJECTA_API Operator* createOperator(void)
    {
        return new AddOperator<CFraction>;
    }
    OBJECTA_API Var* createVar(void)
    {
        return new VarT<CFraction>( CFraction(1,4) );
    }
    
    CFraction::CFraction() :
    m_iNum (0),
    m_iDenom (0)
    {
    }
    CFraction::CFraction(int iNum, int iDenom) :
    m_iNum (iNum),
    m_iDenom (iDenom)
    {
    }
    CFraction::CFraction(const CFraction& src) :
    m_iNum (src.m_iNum),
    m_iDenom (src.m_iDenom)
    {
    }
    

    DataConsumer

    #include "CommonHeader.h"
    #include "windows.h"
    
    // user-type specialization
    template<>
    struct type_traits<int>
    {
        static const int typeId = 1;
        static const int getId() { return typeId; }
    };
    
    int main()
    {
        Evaluator e;
    
        HMODULE hModuleA = LoadLibrary( "ObjectA.dll" );
    
        if (hModuleA)
        {
            FARPROC pnProcOp = GetProcAddress(hModuleA, "createOperator");
            FARPROC pnProcVar = GetProcAddress(hModuleA, "createVar");
    
            // Prepare function pointer
            typedef Operator*   (*FACTORYOP)();
            typedef Var*        (*FACTORYVAR)();
    
            FACTORYOP fnCreateOp = reinterpret_cast<FACTORYOP>(pnProcOp);
            FACTORYVAR fnCreateVar = reinterpret_cast<FACTORYVAR>(pnProcVar);
    
            // Create object
            Operator*   pOp = fnCreateOp();
            Var*        pVar = fnCreateVar();
    
            AddOperator<int> intOp;
            AddOperator<double> doubleOp;
            e.registerOperator( &intOp, 0 );
            e.registerOperator( &doubleOp, 0 );
            e.registerOperator( pOp, 0 );
    
            VarT<int> i1(10);
            VarT<double> d1(2.5);
            VarT<float> f1(1.0f);
    
            std::cout << "Int Obj id : " << i1.getType() << std::endl;
            std::cout << "Double Obj id : " << d1.getType() << std::endl;
            std::cout << "Float Obj id : " << f1.getType() << std::endl;
            std::cout << "Import Obj id : " << pVar->getType() << std::endl;
    
            Var* i_result = e.evaluate(i1, i1, 0); // result = 20
            Var* d_result = e.evaluate(d1, d1, 0); // no result
            Var* f_result = e.evaluate(f1, f1, 0); // no result
            Var* obj_result = e.evaluate(*pVar, *pVar, 0); // result depend on data provider
            Var* mixed_result1 = e.evaluate(f1, d1, 0); // no result
            Var* mixed_result2 = e.evaluate(*pVar, i1, 0); // no result
    
            obj_result->print();
            FreeLibrary( hModuleA );
        }
        return 0;
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am trying to subclass the android.os.AsyncTask class generically. I basically just want to
I am using AudioQueue to stream audio from an arbitrary source (the class basically
I'm not that familiar with iframes and basically just want to find out if
Basically I just want to put new.gif in the top left corner of the
Basically I just want to check if one time period overlaps with another. Null
I just basically want to add about 20 and sometimes 80 Proximity Alerts with
So, I just basically want to use AVFoundation Kit for playing my sound. I
I just want to ask if anybody has done something like this. Basically, it's
I just want to design this very simple website. Basically there are multiple pages
Basically, I just want to know if its possible to use Nhibernate to migrate

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.