开发者

Operator priority on overloading

开发者 https://www.devze.com 2023-02-05 14:30 出处:网络
I am trying to make a C++ compiled model for simple SQL commands. For example this could be a part of my main function which i must be able to handle :

I am trying to make a C++ compiled model for simple SQL commands. For example this could be a part of my main function which i must be able to handle :

CREATE_TABLE(books) [             // create("books");ovr[
    COLUMN(c1) TYPE(string),      // "title string",
    COLUMN(c2) TYPE(string),      // "author string",
    COLUMN(num1) TYPE(int)        // "price int"
                    ];

So in order to do that i had to o开发者_如何转开发verload the "[]" and "," operators. After doing so, I figured out that the "," overloader is executed before the "[]" one. Whereas my guess would be that "[]" should be executed first. Is there any particular reason why this happens? Or is it simply because the "[]" is executed when "]" is found?


Your expression would be compiled to something like the following, which might explain the evaluation order:

CREATE_TABLE(books).operator[](
    COLUMN(c1) TYPE(string).operator,(
        COLUMN(c2) TYPE(string).operator,(
            COLUMN(num1) TYPE(int) 
        )
    )
);

or

CREATE_TABLE(books).operator[](
    operator,( COLUMN(c1) TYPE(string), 
        operator,( COLUMN(c2) TYPE(string), COLUMN(num1) TYPE(int))
    )
);

depending on how your operator,() is defined (and maybe how the COLUMN and TYPE macros are defined).


The expression inside the [] has to be evaluated first - it needs to be passed in as the argument, which is why you see the operator, being called first.


Because in order to call operator[], it needs a single parameter. It treats what's inside the brackets as an expression with commas, and uses operator, to get a single result with which to call your operator[].


Because the [] operator takes a single argument, it waits for the entire expression between the [] to be evaluated before it is evaluated itself.


It looks like you are using the result of operator,() as the argument of operatot[](), so it's only logical that the former is evaluated first, as in f(g(x)).

Also, nothing is "parsed" at runtime. C++ is a compiled language.

0

精彩评论

暂无评论...
验证码 换一张
取 消