[C++-sig] () and [] operators

Bjorn Pettersen BPettersen at NAREX.com
Wed Nov 13 00:33:44 CET 2002

> From: Kerim Borchaev [mailto:warkid at hotbox.ru] 
>   I wasn't able to find an "intuitive"(like for other 
> operators) way to expose () and []
>   operators. How am I supposed to do it?

The () operator should be pretty straight forward binding to __call__,
however operator[] must raise a Python IndexError when called with an
out of range argument (e.g. the old for loop protocol required this and
it is still used for objects that don't define __iter__). Here's example
code from wrapping our internal string class, NString:

namespace {
	char NString_get_item(NString& self, int index) {
		if (index >= self.size()) {
		return self[index];

void wrap_NString() {

	class_<NString, bases<NObject> >("NString", init<char*>())
		.def("__getitem__", &NString_get_item)


(basically, just bind __getitem__ to a standalone function that does the
index checking...)

-- bjorn

More information about the Cplusplus-sig mailing list