Search code examples
c++constructorc++14chaiscriptstdinitializerlist

How call a constructor with std::initializer_list of a user type in ChaiScript?


I have the next definition class:

class MyType {
public:
    MyType();
    MyType(int x);
    MyType(std::initializer_list<MyType> list);
}

I register my custom class and its constructors in ChaiScript v6.0.0 as follows:

chai.add(chaiscript::user_type<MyType>(), "MyType");
chai.add(chaiscript::constructor<MyType()>(), "MyType");
chai.add(chaiscript::constructor<MyType(int)>(), "MyType");
chai.add(chaiscript::constructor<MyType(std::initializer_list<MyType>)>(), "MyType");

I have the next scripts:

std::string script1 = R""(
    def Test1() {
        var m = MyType();
    }

    Test1();
)"";
auto res = chai.eval<MyType>(script1);


std::string script2 = R""(
    def Test2() {
        var m = MyType(10);
    }

    Test2();
)"";
auto res2 = chai.eval<MyType>(script2);


std::string script3 = R""(
    def Test3() {
        var m = MyType({10, 20});
    }

    Test3();
)"";
auto res3 = chai.eval<MyType>(script3);

script1 and script2 run without problems, but script3 give me the next execution error:

Error: "Incomplete equation" during evaluation  at (9, 14)

What is the correct way to call the constructor MyType(std::initializer_list<MyType>) from ChaiScript?


Solution

  • ChaiScript doesn't have a way to register a variadic function, it is necessary register a function for each possible combination of arguments and cannot manufacture braced-init-list like C++.

    The workaround that I found was to add a constructor for MyType that receive a vector:

    class MyType {
    public:
        MyType();
        MyType(int x);
        MyType(std::initializer_list<MyType> list);
        MyType(const std::vector<MyType>& v);
    }
    

    Register my custom class and its constructors in ChaiScript v6.0.0 as follows:

    chai.add(chaiscript::user_type<MyType>(), "MyType");
    chai.add(chaiscript::constructor<MyType()>(), "MyType");
    chai.add(chaiscript::constructor<MyType(int)>(), "MyType");
    chai.add(chaiscript::constructor<MyType(const std::vector<MyType>&)>(), "MyType");
    

    And change script3 for:

    std::string script3 = R""(
        def Test3() {
            var m = MyType([MyType(10), MyType(20)]);
        }
    
        Test3();
    )"";