浏览代码

Improve NOMORE, NOLESS, and LIMIT macros

etagle 7 年前
父节点
当前提交
06fd4d7b28
共有 1 个文件被更改,包括 44 次插入4 次删除
  1. 44
    4
      Marlin/src/core/macros.h

+ 44
- 4
Marlin/src/core/macros.h 查看文件

@@ -91,10 +91,50 @@
91 91
 #define SIGN(a) ((a>0)-(a<0))
92 92
 #define IS_POWER_OF_2(x) ((x) && !((x) & ((x) - 1)))
93 93
 
94
-// Macros to contrain values
95
-#define NOLESS(v,n) do{ if (v < n) v = n; }while(0)
96
-#define NOMORE(v,n) do{ if (v > n) v = n; }while(0)
97
-#define LIMIT(v,n1,n2) do{ if (v < n1) v = n1; else if (v > n2) v = n2; }while(0)
94
+// Macros to constrain values
95
+// Avoid double evaluation of arguments to NOMORE/NOLESS/LIMIT
96
+#undef NOMORE
97
+#undef NOLESS
98
+#undef LIMIT
99
+#ifdef __cplusplus
100
+
101
+  // C++11 solution that is standards compliant.
102
+  template <class V, class N> static inline constexpr void NOLESS(V& v, const N n) {
103
+    if (v < n) v = n;
104
+  }
105
+  template <class V, class N> static inline constexpr void NOMORE(V& v, const N n) {
106
+    if (v > n) v = n;
107
+  }
108
+  template <class V, class N1, class N2> static inline constexpr void LIMIT(V& v, const N1 n1, const N2 n2) {
109
+    if (v < n1) v = n1;
110
+    else if (v > n2) v = n2;
111
+  }
112
+
113
+#else
114
+
115
+  // Using GCC extensions, but Travis GCC version does not like it and gives
116
+  //  "error: statement-expressions are not allowed outside functions nor in template-argument lists"
117
+  #define NOLESS(v, n) \
118
+    do { \
119
+      __typeof__(n) _n = (n); \
120
+      if (v < _n) v = _n; \
121
+    } while(0)
122
+
123
+  #define NOMORE(v, n) \
124
+    do { \
125
+      __typeof__(n) _n = (n); \
126
+      if (v > _n) v = _n; \
127
+    } while(0)
128
+
129
+  #define LIMIT(v, n1, n2) \
130
+    do { \
131
+      __typeof__(n1) _n1 = (n1); \
132
+      __typeof__(n2) _n2 = (n2); \
133
+      if (v < _n1) v = _n1; \
134
+      else if (v > _n2) v = _n2; \
135
+    } while(0)
136
+
137
+#endif
98 138
 
99 139
 // Macros to support option testing
100 140
 #define _CAT(a, ...) a ## __VA_ARGS__

正在加载...
取消
保存