对于使用任意类型的给定参数进行任意操作有什么建议吗?

发布于 2024-08-23 17:17:47 字数 1945 浏览 13 评论 0原文

基本上我只想使用任意类型的给定参数进行任意操作。

参数类型基类是 Var,Operation 是将针对给定参数执行的操作的基类。

我有 Evaluator 类,它包含使用 opId 映射的运算符集合。评估器将根据evaluate()成员函数中给出的opId参数进行操作,然后evaluate()函数将搜索接受参数类型和opId的支持的运算符。

我想问的是,是否有任何有效的模式或算法可以无需dynamic_cast<>来做到这一点?和/或循环操作符集合

`

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();
    }
}

`

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();
    }
}

`

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

⊕婉儿 2024-08-30 17:17:47

如果您不想使用dynamic_cast,请考虑在您的设计中添加类型特征。

添加 05/03/10 :以下示例将演示运行时特征如何工作

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 标头

#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 实现

#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;
}

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;
}
溺深海 2024-08-30 17:17:47

如果您可以修改类型 Var,您可以为参数类型添加 type-Id。但在操作的实现过程中,您总是必须在某些时候使用dynamic_cast。如果您的类型和操作在编译时是固定的,则可以使用 Boost.MPL(特别是容器)。

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).

懷念過去 2024-08-30 17:17:47

您的示例代码包含许多错误,包括切片问题。

我不是 100% 确定,但我似乎记得您可以使用 const type_info* 作为地图的键。

如果是这样,您可以使用如下所示的内容。它并非不受 RTTI (type_info) 的影响,但由于 Evaluator 已经检查了 typeid,因此您可以使用 static_cast 而不是 dynamic_cast(但是现在代码不再盲目搜索要应用的正确运算符,这并不重要)。

当然,下面在内存管理方面就完全被打破了。使用您选择的智能指针重新实现。

#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
}

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
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文