Skip to main content
gamedev.net
🔒 Locked

operator [ int, int ]

Started by thedustbustr Dec 24, 2004 at 12:15 AM 2 replies 350+ views
Original Post
thedustbustr
thedustbustr
Is it possible to overload the subscript operator[] and the comma operator, such that you could call myObject[2,5] (similar to python string splicing, mystr[2:5])?
eleusive
eleusive
Which language are you talking about?
"What are you trying to tell me? That I can write an O(N^2) recursive solution for a 2-dimensional knapsack?" "No, programmer. I'm trying to tell you that when you're ready, you won't have to." -Adapted from "The Matrix"
Polymorphic OOP
Polymorphic OOP
Quote:
Original post by thedustbustr
Is it possible to overload the subscript operator[] and the comma operator, such that you could call myObject[2,5] (similar to python string splicing, mystr[2:5])?

Assuming you mean C++, you can't overload operator[] to take 2 parameters, and you can't overload the comma operator for built-in types, however, you can if one of the operands of the comma operator is a type you define. In that case, you can use expression templates instantiated with each comma operation. Alternatively, if you aren't used to expression templates and you only ever want 2 operands (never 3, etc), you can just make your type have a constructor taking 2 operands.

In other words:

// Prefered solutionmyObject[ your_type(2), 5 ];myOtherObject[ your_type(2), 5, 6 ];// Or, the alternative solutionmyObject[ your_type(2, 5) ];myOtherObject[ your_other_type(2, 5, 6) ];


Note that the first solution allows you to easily work with the same "your_type" to start the expression, whereas the alternative solution requires a different type depending on the number of operands and is not easily expandable for more parameters without having to resort to preprocessor metaprogramming, though if you only want it for 2 or 3 parameters, it will be easier to implement.
SiCrane
SiCrane
A better approach might be to overload operator() instead.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.