【问题标题】:Macro Overloading with Different Signatures不同签名的宏重载
【发布时间】:2015-09-18 03:34:12
【问题描述】:

是否可以重载可以使用相同的宏名称执行不同运算符(=、+=、-=、++、--等)的宏?

我想实现这样的目标:

int main() {
    LOG_STAT("hello") << "world";
    LOG_STAT("hello") = 5;
    LOG_STAT("hello") += 10;
}

我尝试了以下方法,但我遇到的问题是我无法重新声明已定义的宏 LOG_STAT。下面的示例代码,希望你能明白。

#define LOG_STAT(x) Stat(x).streamAdd()

#define LOG_STAT(x) Stat(x).add() // redeclare error here

class Stat {

    public:
        Stat(const char *type_ ) : type(type_) {}
        ~Stat(){ std::cout << type << " " << stream.str().c_str() << " " << number << std::endl;}

        int& add() { return number; }
        std::ostringstream& streamAdd() { return stream; }

        const char * type;
        int number;
        std::ostringstream stream;
};

【问题讨论】:

  • LOG_STAT("hello") += 10; 应该是什么意思?尤其是 LOG_STAT(...)std::ostream..
  • 宏是邪恶的。如果必须,创建一个重载这些运算符的类以执行您想要的操作。
  • @BillLynch 只是重载的另一个例子。例如,+= 会增加 stat 类中的数字。在上面的示例中,当被析构函数调用时,该值将是 15。
  • @NeilKirk 是的,我越想越觉得你是对的。我只是想看看这样的事情是否可能是可能的。
  • 宏发生,至少在概念上,在编译器理解操作符之前很长一段时间。所以不,你不能对宏这样做。

标签: c++ gcc macros


【解决方案1】:

为您的班级创建运算符:

Stat& Stat::operator += (int rhs)
{
    number += rhs;
    return *this;
}

Stat operator + (const Stat& lhs, int rhs)
{
    Stat res(lhs);
    res += rhs;
    return res;
}

template <typename T>
Stat& operator << (Stat& stat, const T&value)
{
    stat.stream << value;
    return stat;
}

那么你可以直接使用

Stat("hello") << "world";
Stat("hello") = 5;
Stat("hello") += 10;

(您仍然可以将 MACRO 与 #define LOG_STAT Stat 一起使用)

【讨论】:

    猜你喜欢
    • 2013-02-23
    • 1970-01-01
    • 2018-07-16
    • 1970-01-01
    • 1970-01-01
    • 2015-06-09
    • 1970-01-01
    • 1970-01-01
    • 2012-08-12
    相关资源
    最近更新 更多