Overloading the () operator in ChaiScript


I’m trying to overload the “()” in ChaiScript.

Currently the “[]” operator works perfectly. However, the “()” operator seems to be wrongly intepreted as a function call.

Below is my test:

I have a C++ type:

class Mat {
	std::string operator()(const int i) {
		std::stringstream s;
		s << "I am (" << i << ")" << endl;
		return s.str();
	std::string operator[](const int i) {
		std::stringstream s;
		s << "I am [" << i << "]" << endl;
		return s.str();

The way I am currently adding my type is quite straightforward:

chai.add(chaiscript::user_type<Mat>(), "Mat");
chai.add(chaiscript::constructor<Mat()>(), "Mat");
chai.add(chaiscript::fun(static_cast<string(Mat::*)(const int)>(&Mat::operator())), "()");
chai.add(chaiscript::fun(static_cast<string(Mat::*)(const int)>(&Mat::operator[])), "[]");

My test in ChaiScript is:

chai> var m = Mat()
chai> m[1]
I am [1]

chai> m(1)
Error: "'m' does not evaluate to a function." during evaluation at (1, 1)

How do I correctly overload the “()” operator for a class in ChaiScript?


It is not currently possible, you can see a discussion about it here:

it’s actually a pretty complex issue to try and support it.


My current workaround is a by making a one letter function:

chai.add(chaiscript::fun(static_cast<string(Mat::*)(const int)>(&Mat::operator())), “f”);

This way I can call the operator like:

chai> m.f(1)
I am (1)

However it would be nicer if I could call it with a nameless function like:

chai> m.(1)
Error: “Incomplete dot access fun call” during evaluation at (1, 3)

Would supporting this feature reduce the runtime penalty of the “()” operator?


Interesting possibility, it’s something I could look into.

Would you mind adding a note about this proposal on the github issue?