在 C++ 中是否有一种简单的方法来拥有一个允许使用变量的消息查找表。
例如在 C 中你可以有这样的东西:
const char* transaction_messages[] = {
"UNAUTHORIZED",
"UNKNOWN_ORDER",
"UNKNOWN_DEALER",
"UNKNOWN_COMMODITY",
"INVALID_MESSAGE",
"BOUGHT %d %s @ %f.1 FROM %s", //amount, commodity, price, dealer
"SOLD %d %s @ %f.1 FROM %s", //amount, commodity, price, dealer
"%d HAS BEEN FILLED", //order id
"%d HAS BEEN REVOKED", //order id
"%d %s %s %s %d %f.1 HAS BEEN POSTED", //order id, dealer, side, commodity, amount, price
"%d %s %s %s %d %f.1" //order id, dealer, side, commodity, amount, price
};
然后在这样的函数中使用它:
void myfunction(int amount, char* commodity, double price, char* dealer){
char *msg = transaction_message[6];
printf(msg, amount, commodity, price, dealer);
}
我希望能够对 ostream 执行相同操作,而不必对 << 运算符执行相同的操作:
ostream << "BOUGHT" << amount << " " << commodity << " @ " << price << " FROM " << dealer;
我现在能想到的唯一方法是拥有一堆返回字符串的内联函数,而不是拥有一个 char* 表,而是拥有一个查找内联函数的函数表。必须有一个更简单的方法。