Search code examples
c++operatorsexpressionoperator-keyword

How to make an "operator" variable? (C++)


I am working on making an expression class:

template<typename T, typename U>
class expression
{
public:
    expression(T vala, U valb, oper o){val1 = vala; val2 = valb; op = o;}
    operator bool{return(val1 op val2);}
private:
    T val1;
    U val2;
    oper op;
};

as you can see, this is somewhat pseudocode, because I need an operator class. My original thought was to create an array of all possible operators, and then convert it through a string, but that wouldn't work because of the sheer number of operators, and how to convert it to a string except through a two dimensional array, where n[0][0] has the first operator, and n[0][1] has that operators string.

Does anybody have any suggestions to adding an operator value to my expression class?


Solution

  • Maybe a function pointer. Instead of ...

    operator bool{return(val1 op val2);}
    

    ... code it as ...

    operator bool{return op(val1, val2);}
    

    ... in which case op can be a pointer to a (any) function which takes two parameters and which returns bool.

    template<typename T, typename U>
    class expression
    {
    public:
        //define pointer-to-function type
        typedef bool *oper(const T& val1, const U& val2);
        ... etc ...