다음을 통해 공유


C++/CLI operators

A bit of background. You may recall CLI operators in Managed Extensions: op_Equality, op_Addition, ... so on and so forth. To be sure, not the friendliest set of operators ever, as you had to remember what their names were in order to overload them.

How is it different in Whidbey? We're leveraging the existing C++ operator overloading syntax for CLI operators. So you can have code like the following:

public ref class Point{

private:

      int x;

      int y;

public:

      static Point^ operator+(Point^ a, Point^ b);

      static Point^ operator*(Point^ a, Point^ b);
static Point^ operator+(Point^ a, int x);
};

Why is the operator defined in terms of handles (^)? First of all, because I haven't explained the tracking reference (%) yet. (But you could also define operators in terms of it.) Secondly, because handles are how you typically have access to ref types - they don't go on the stack, remember. Finally, because you can't normally perform addition on a handle anyhow - it isn't like native pointers, there's no guarantee about how the GC Heap is arranged.

 

There are other differences... Also, note that both parameters are listed in the operator (instead of just the right-hand one), that's because we can't be sure what the type of the left-hand operator is going to be. Also, it is a requirement of the CLI that operators be marked static.

 

What happens to these operators? They're still emitted in IL as the op_Addition, op_Multiplication, etc. functions - we're just exposing them through an interface that's hopefully more comfortable and recognizable to C++ users.