GideonMax
GideonMax

Reputation: 604

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.

Upvotes: 2

Views: 1015

Answers (2)

Yaroslav Stetsyk
Yaroslav Stetsyk

Reputation: 160

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

Upvotes: 2

t.niese
t.niese

Reputation: 40882

A typedef is not a new type, it just creates an alias, your Expression is still the type std::function<uint64_t(uint64_t)>.

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.

It isn't fundamentally impossible (in the sense that the specification could not allow such a thing), but there is no such functionality given in the specification so you can't do it. Just as it is not possible to add a new member function to an existing type.

Upvotes: 4

Related Questions