我想知道是否可以在C++中使用宏或内联函数执行4个操作。在C++中为特定函数定义宏
(1) postfix operations in normal types (int, char, etc)
int n = 5;
printf("%d\n", n!)
output: 120
(2) infix operations in normal types (int, char, etc)
int a = 20, b = 10
if(b|a) printf("%d is divisor of %d\n", b, a);
// the symbol | means "divides", this is like (a % b == 0)
output: 10 is divisor of 20
(3) sequential operations in common types
int a = 5, b = 15, c = 20;
if(a < b < c) printf("true\n");
output: false
//doesn't matter if it's made with symbols or words
(4) for each (not using for(auto...) C++11) and
it may different for lists, vectors, etc...
vector<int> v = {1,3,5,7};
foreach(e : v) printf("%d ", e);
output: 1 3 5 7
就是这样。是否有可能在C++中创建这些宏?
谢谢!
PS:符号不需要|要么 !。既然他们工作,他们可以是@或$或任何东西。这个想法是后缀(a @),中缀(a @ b),顺序(a @ b @ c)和foreach可能不同,只是小于正常值而已。
**不要使用宏**,你只是为这些片段提供内嵌的功能。 –
宏在这里不能使用,因为它们的名字必须是标识符(不是'''等操作符)。而C++不允许运算符重载内建类型。我想你可以用你自己的特殊预处理器来完成这个任务,但是在那个时候,你并不是真的在写C++,所以你不妨使用不同的语言或者更传统的语法。 – Cameron
我很好奇,如果我可以做到这一点......如果语法与所示相同,我不在乎它的宏或内联......但我更喜欢宏,因为它的代码较小,符号可以是除了那些被禁止的,没有问题的那个 – Daniel