views:

139

answers:

3

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  A: 

If you can modify the type Var you could add type-Ids for the argument types. But in the implementation of your operations you would always have to use a dynamic_cast at some point. If your types and operations are fixed at compile-time, you can do the whole thing with templates using Boost.MPL (specifically the containers).

Space_C0wb0y
unfortunately both operator and type is dynamic, for example a DLL could introduce new operator by mapping it to Evaluator, or submit some fancy type of argument to the Evaluator. I could add Type-Id to Var class, since type-id must be unique across application and I should give it at runtime, does it worth the complexity? implementation example? using Singleton class to give newly introduced type at runtime perhaps?
uray
Yes, a singleton would be appropriate. Maybe some Registry-class, to which all operations have to be registered, and which would assign Ids.
Space_C0wb0y
+2  A: 

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;
}
YeenFei
Do type traits work with inheritance? I mean, if I have a reference to an object through it's baseclass, can I get the traits of the actual type? Also, how would you accomodate new operations that get added at runtime?
Space_C0wb0y
you just need to add member function that return information of type traits. i will scratch some code to illustrate it later
YeenFei
I don't think by using type traits it will work, if operator or type are supplied by DLL which loaded at run-time by the Apps, since by using type traits the Apps need to include the header file which those templated type reside at compile time, isn't it?
uray
uray: it will work since we are retrieving the type info using function instead of pure-type-traits style (compiler selection). Everything i posted (minus type_traits<int> and type_traits<double>) is the base header. you can have your custom object (ie CMatrix) in separate source file, as long as they provide necessary specialization for themselves to compile, object user in other DLL will not care and continue to work like normal.
YeenFei
ic, then for int typeId value, it should be centralized managed since every id must be unique right? in case a new type is introduced by DLL, DLL should ask for unique typeId from App
uray
uray : yes, if you are using int typeId, you need to implement certain mechanism to prevent type collision. I have updated the code sample to show it work in DLL scenario.
YeenFei
thanks for the codes, that really help. if the DLL writers are myself, I will go with type traits since it is more elegant and clear, but I think it is too complicated for my client (DLL author) to extend my App if they must write their on template specialization, i think given the explanation of how it work, it is enough to just using virtual function getType() on Var class that will return the type-id that will be auto assigned by Var Repository, so the client just need to register it and doesn't need to know about the type-id values. how do you think?
uray
I'm not sure how your Var Repository works, but any careful designed architecture will work
YeenFei
@uray: if you cannot rely on the getId(), you may rely on another technic `typeid(5).name()` will give you a `const char*` that is guaranted to be unique (though not comparable to one from another compiler). For `gcc` it yields the mangled name, for example, so unless you have a symbol collision, you're fine.
Matthieu M.
+1  A: 

Your sample code contains many errors, including slicing problems.

I'm not 100% sure, but I seem to remember you can use const type_info* as a key for a map.

If so, you could use something like following. It is not free from RTTI (type_info), but since Evaluator already checks the typeids, you can use a static_cast instead of a dynamic_cast (but it isn't that important now that the code doesn't blindly search for the right operator to apply).

Of course, the following is completely broken in terms of memory management. Reimplement with smart pointers of your choice.

#include <map>
#include <typeinfo>
#include <cassert>

#include <iostream>

struct CompareTypeinfo
{
    bool operator()(const std::type_info* a, const std::type_info* b) const
    {
        return a->before(*b);
    }
};

class Var {
public:
    virtual ~Var() {}
    virtual const std::type_info& getType() const = 0;

    virtual void print() const = 0;
};

template<typename T> class VarT : public Var {
    T value;
public:
    VarT(const T& v): value(v) {}
    const T& getValue() const { return value; }
    virtual const std::type_info& getType() const { return typeid(T); }  

    virtual void print() const { std::cout << value << '\n'; } 
};

class Operator {
public:
    virtual ~Operator() {}
    virtual Var* evaluate(const Var& a, const Var& b) const = 0;
    virtual const std::type_info& getType() const = 0;
};

template<typename T> class AddOperator : public Operator {
public:
    typedef T type;
    virtual const std::type_info& getType() const { return typeid(T); }
    virtual Var* evaluate(const Var& a, const Var& b) const
    {   
        //it is the responsibility of Evaluator to make sure that the types match the operator            
        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());
    }
};

class Evaluator {
private:
    typedef std::map<const std::type_info*, Operator*, CompareTypeinfo> TypedOpMap;
    typedef std::map<int, TypedOpMap> OpMap;
    OpMap operatorMap;
public:
    template <class Op>
    void registerOperator(int opId)
    {
        operatorMap[opId].insert(std::make_pair(&typeid(typename Op::type), new Op));
    }
    Var* evaluate(const Var& a, const Var& b,int opId)
    {
        OpMap::const_iterator op = operatorMap.find(opId);
        if (op != operatorMap.end() && a.getType() == b.getType()) {
            TypedOpMap::const_iterator typed_op = op->second.find(&a.getType());
            if (typed_op != op->second.end()) {
                //double-checked
                assert(typed_op->second->getType() == a.getType());
                return typed_op->second->evaluate(a, b);
            }
        }
        return 0;
    }
};

int main()
{
    Evaluator e;

    e.registerOperator<AddOperator<int> >(0);
    e.registerOperator<AddOperator<double> >(0);

    VarT<int> i1(10), i2(20);
    VarT<double> d1(2.5), d2(1.5);
    VarT<float> f1(1.0), f2(2.0);

    Var* i_result = e.evaluate(i1, i2, 0);
    Var* d_result = e.evaluate(d1, d2, 0);
    Var* f_result = e.evaluate(f1, f2, 0);
    Var* mixed_result = e.evaluate(i1, d2, 0);

    assert(i_result != 0);
    assert(d_result != 0);
    assert(f_result == 0); //addition not defined for floats in Evaluator
    assert(mixed_result == 0); //and never for mixed types

    i_result->print(); //30
    d_result->print(); //4.0
}
visitor
yeah the code is just for illustration, its not the actual code, i just write it on notepad, thanks for your suggestion, I'll read your codes for a while...
uray