在我的 C 應用程式中,我以這種方式配置了一些功能:
#define LED_SIZE 113
#define SEGMENT_SIZE 3
const int LED_SEGMENTS[SEGMENT_SIZE] = {30, 70, 13};
我想檢查文字值的總和是否等于LED_SIZE:
30 70 13 = 113
我有興趣在編譯時使用前處理器指令執行此操作。如果總和不正確,則不應編譯。
uj5u.com熱心網友回復:
您可以使用static_assert
#define LED_SIZE 113
#define SEGMENT_SIZE 3
constexpr int LED_SEGMENTS[SEGMENT_SIZE] = {30, 70, 13}; // this need to be constexpr
#include <numeric>
static_assert(
std::accumulate(LED_SEGMENTS,LED_SEGMENTS SEGMENT_SIZE,0) == LED_SIZE
);
注意:std::accumulate僅從constexprc 20 開始,您可能需要為早期標準撰寫自定義。
uj5u.com熱心網友回復:
避免使用 C 前處理器。
#include <array>
#include <numeric>
constexpr int LED_SIZE = 113;
constexpr int SEGMENT_SIZE = 3;
constexpr std::array<int, SEGMENT_SIZE> values{30, 70, 13};
static_assert(std::accumulate(values.begin(), values.end(), 0) == LED_SIZE);
uj5u.com熱心網友回復:
使用前處理器指令
無法使用前處理器指令訪問陣列。LED_SEGMENTS[0]字面意思LED_SEGMENTS[0]是前處理器,前處理器中沒有陣列訪問。
您可以在前處理器世界中使用它,然后撰寫一個可變引數多載引數宏來計算逗號分隔串列的總和:
#define LED_SIZE 113
#define SEGMENT_SIZE 3
#define LED_SEGMENTS 30, 70, 13
#define SUM_1(a) a
#define SUM_2(a, ...) a SUM_1(__VA_ARGS__)
#define SUM_3(a, ...) a SUM_2(__VA_ARGS__)
#define SUM_4(a, ...) a SUM_3(__VA_ARGS__)
#define SUM_N(_4,_3,_2,_1,N,...) SUM##N
#define SUM_IN(...) SUM_N(__VA_ARGS__,_4,_3,_2,_1)(__VA_ARGS__)
#define SUM(...) SUM_IN(__VA_ARGS__)
#if SUM(LED_SEGMENTS) != LED_SIZE
#error "SUM(LED_SEGMENTS) != LED_SIZE"
#endif
在編譯時執行此操作
你應該使用:
#include <functional>
#include <numeric>
#define LED_SIZE 113
#define SEGMENT_SIZE 3
constexpr int LED_SEGMENTS[SEGMENT_SIZE] = {30, 70, 13};
static_assert(std::accumulate(std::begin(LED_SEGMENTS), std::end(LED_SEGMENTS), 0) == LED_SIZE);
uj5u.com熱心網友回復:
您可以使用#if前處理器指令:
#define LED_SIZE 113
#define SEGMENT_SIZE 3
const int LED_SEGMENTS[SEGMENT_SIZE] = {30, 70, 13};
#if (LED_SEGMENTS[0] LED_SEGMENTS[1] LED_SEGMENTS[2] != LED_SIZE)
#error "sum of LED segments is not equal the total LED size"
#endif
(未經測驗)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/521608.html
標籤:C c-预处理器
