Overloading the () operator in ChaiScript


#1

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 {
public:
	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)
chai>

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


#2

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.


#3

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?


#4

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

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