Search code examples
c++typedef

c++ how to make constructor for typedef type


In my c++ project I have a type called Expression

typedef std::function<uint64_t(uint64_t)> Expression;

I also have a function which acts like a constructor

Expression ExpressionConstructor(std::string Expr, MicroCodeDescriptor* descriptor) {
//implementation doesn't matter in this case
}

This code works, I can use the Expression type like this:

Expression expr= ExpressionConstructor(code, descriptor);

But is there any way to declare a constructor for Expression that syntactically works like a constructor instead of like a separate function, I don't see any reason why this is fundamentally impossible as constructors are just functions with the return type of the class they construct.


Solution

  • Instead of typedef your Expression could be a class derived from std::function<uint64_t(uint64_t)>. Then you can define its constructor(s), destructor and call it as a std::function:

    struct Expression : public std::function<uint64_t(uint64_t)>
    {
        Expression(std::string Expr, MicroCodeDescriptor* descriptor)
        {
    
        }
    };
    
    Expression e = Expression("", nullptr);
    uint64_t res = e(123);
    

    Or even better make it template:

    template<typename R = uint64_t, typename T = uint64_t>
    struct Expression : public std::function<R(T)>
    ...