具有不同签名的宏重载
Macro Overloading with Different Signatures
是否可以使用相同的宏名称重载可以执行不同运算符(=、+=、-=、++、-- 等)的宏?
我想实现这样的目标:
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;
};
为您的 class 创建运算符:
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
一起使用)
是否可以使用相同的宏名称重载可以执行不同运算符(=、+=、-=、++、-- 等)的宏?
我想实现这样的目标:
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;
};
为您的 class 创建运算符:
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
一起使用)