具有不同签名的宏重载

Macro Overloading with Different Signatures

本文关键字:重载      更新时间:2023-10-16

是否可以重载可以使用相同宏名称执行不同操作符(=,+=,-=,++,——等)的宏?

我想实现这样的事情:

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;
};

为类创建操作符:

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;

(您仍然可以使用您的宏与#define LOG_STAT Stat)