SomeRanDev / reflaxe.CPP

An alternative C++ target for Haxe that generates dependent-less, GC-less C++17 code.
MIT License
72 stars 5 forks source link

struct generation is a bit redundant. #26

Closed sonygod closed 1 year ago

sonygod commented 1 year ago

I think your struct generation is a bit redundant.

typedef Person ={

    var name:String;
    var age:Int;
    var ?address:String;
} 

and your code

#pragma once

#include <optional>
#include <string>
#include "_AnonStructs.h"

// { age: Int, name: String, address: Null<String> }
struct Person {

    // default constructor
    Person() {}

    // auto-construct from any object's fields
    template<typename T>
    Person(T o):
        age(haxe::unwrap(o).age),
        name(haxe::unwrap(o).name),
        address(extract_address(haxe::unwrap(o)))
    {}

    // construct fields directly
    static Person make(int age, std::string name, std::optional<std::string> address = std::nullopt) {
        Person result;
        result.age = age;
        result.name = name;
        result.address = address;
        return result;
    }

    // fields
    int age;
    std::string name;
    std::optional<std::string> address;

    GEN_EXTRACTOR_FUNC(address)
};

I think it's too heavy to use .

why not like this ?

struct Person {
    std::string name;
    int age;
    std::optional<std::string> address; 
};
sonygod commented 1 year ago

May be your code is for some reason.

The goal of designing the struct in this way is to provide multiple ways of constructing Person objects based on different scenarios. By including these various constructor options, the struct becomes more versatile, allowing users to create Person objects using their preferred method based on the available data or requirements.

SomeRanDev commented 1 year ago

Yes! Apologies for the delay, but a Haxe "anonymous structure" is very different from a C++ struct. An anonymous structure needs to be able to be assigned from any object with the same fields, like this:

class Test { var a: Int = 0; }

function main() {
    final test = new Test();
    doThing(test);
}

function doThing(num: { a: Int }) {
    // do something with an object with "a: Int"
}

So that's why there needs to be a lot of boilerplate. If you want a "struct", you can create a Haxe class with just fields in it. class and struct do the same thing in C++ afaik!