如何在c ++中为宏执行运算符重载 [英] How to do operator overloading for a macro in c++

查看:107
本文介绍了如何在c ++中为宏执行运算符重载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想根据参数的数量重载一个宏



例如:BAR() - >当我在没有争论的情况下调用它时应该调用

BAR(x) - >当用参数调用时。



我看到很多类似的问题发布在其他网站上,我可以看到建议重载的解决方案是通过改变像BAR这样的宏的名称(),BAR_Z(x)。



发布的解决方案之一是:

I want to overload a macro based on the number of arguments

For eg: BAR()--> should be called when I call it without an argument
BAR(x)--> when called with argument.

I saw many similar questions posted in other sites and I could see that the solution suggested for overloading is by changing the name of the macro like BAR(), BAR_Z(x).

One of the solution posted was:

#define MY_GLUE(x, y) x y
    #define MY_ASSERT1(x) \
    do \
    {\
    do something with x \
    } while (false);
     
    #define MY_ASSERT2(x, y) \
    do \
    {\
    do other things with x and y \
    } while (false);
     
     
    #define MY_ASSERT_CHOOSE_HELPER2(count) MY_ASSERT##count
    #define MY_ASSERT_CHOOSE_HELPER1(count) MY_ASSERT_CHOOSE_HELPER2(count)
    #define MY_ASSERT_CHOOSE_HELPER(count) MY_ASSERT_CHOOSE_HELPER1(count)
    #define ASSERT(...) \
    MY_GLUE(MY_ASSERT_CHOOSE_HELPER(COUNT_ARGS(__VA_ARGS__)), (__VA_ARGS__))
     
    void test(void) {
    int a = 0, b = 1;
    ASSERT(a == 0);
    ASSERT(a == 0, b == 1);
    }



这里MY_ASSERT1和MY_ASSERT_2是宏。



根据我对运算符重载的了解函数的名称保持不变,并根据参数的类型和数量调用特定函数。



我在哪里看到建议的解决方案有所不同名字。



然后如何证明重载C ++的概念是合理的。?



请纠正我,如果我我错了,因为我是C ++的新手。


Here MY_ASSERT1 and MY_ASSERT_2 are macros.

As per my knowledge on operator overloading the name of the function remains the same, and the specific function is called based on the type and number of arguments.

Where as I see that the solution suggested had different name.

Then how does it justify overloading concept of C++.?

Please correct me if I am mistaken, as I am new to C++.

推荐答案

运算符重载仅适用于C ++函数而不适用于宏。考虑到宏由预处理器扩展,因此对于以下编译步骤不再可见。虽然宏可能看起来像你的功能,但它们实际上并非如此。
Operator overloading only applies to C++ functions and not to macros. Consider that macros are expanded by the preprocessor and and are hence are no longer visible to the following compilation steps. Although macros might look like functions to you they are in fact not.


C ++提供了许多高级功能,只是为了摆脱宏。

嗯,当然不是这样。但是,除非您只是想强调预处理器的耐心,否则最好使用C ++自己的功能(例如模板)而不是此类文件。
C++ provides many advanced features just to get rid of macros.
Well, that's not true, of course. However, unless you just want to stress the patience of the preprocessor, you'd better use C++ own features (e.g. templates) instead of such relics.


这篇关于如何在c ++中为宏执行运算符重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆