Skip to content

Any progress of class static member implemention #531

Description

@Climber7
#include <fstream>
#include <memory>
#include <sstream>
#include <iostream>
#include <chaiscript/chaiscript.hpp>
#include <tinyformat.h>

template<typename T>
class Size_ {
public:
    Size_(T _x, T _y) : x(_x), y(_y) {}

    Size_() : x(0), y(0) {}

    inline T area() {
        return x * y;
    }

    static inline T area(T _x, T _y) {
        return _x * _y;
    }

public:
    T x;
    T y;
};

typedef Size_<int> Size;

std::string readTextFile(const std::string &file) {
    std::fstream in(file);
    std::stringstream ss;
    ss << in.rdbuf();
    in.close();
    return ss.str();
}

void bootstrap(chaiscript::ChaiScript &chai) {
    auto m = std::make_shared<chaiscript::Module>();
    chaiscript::utility::add_class<Size>(
            *m, "Size",
            {
                    chaiscript::constructor<Size()>(),
                    chaiscript::constructor<Size(int, int)>(),
                    chaiscript::constructor<Size(const Size &)>(),
            },
            {
                    {chaiscript::fun([](const Size &size) {
                        return tfm::format("Size{x: %d, y: %d}", size.x, size.y);
                    }),                                                            "to_string"},
                    {chaiscript::fun(&Size::x),                                    "x"},
                    {chaiscript::fun(&Size::y),                                    "y"},
                    {chaiscript::fun(static_cast<int (Size::*)()>(&Size::area)),   "area"},
                    {chaiscript::fun(static_cast<int (*)(int, int)>(&Size::area)), "Size_area"},
            }
    );
    chai.add(m);
}

int main() {
    chaiscript::ChaiScript chai;
    bootstrap(chai);

    auto code = readTextFile("test.chai");
    std::cout << code << std::endl;
    try {
        chai.eval(code);
    } catch (const std::exception &e) {
        std::cout << e.what() << std::endl;
    }

    return 0;
}
var a = Size();
print(a);

var b = Size(100, 100);
print(b);

var c = b;
print(c);

print(c.area());

print(Size_area(10, 10));

There is a static member function.
I'd like to make Size_area to Size::area or Size.area.
What should I do?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions