c 裡如何實現static warning?

時間 2021-06-06 20:22:42

1樓:原子筆

template

X>struct

example;};

//It just declares a function but does not define a variable!!

#define static_warning(x, str) example< ((x)? 0:(1<<30)) > str(example<0>::int_x<__LINE__>)

intmain

()g++ 測試(預設的警告等級):

a.cpp: In function 『int main()』:

a.cpp:7:58: warning: overflow in implicit constant conversion [-Woverflow]

#define static_warning(x, str) example< ((x)? 0:(1<<30)) > str(example<0>::int_x<__LINE__>)

a.cpp:11:2: note: in expansion of macro 『static_warning』

static_warning(false, do_not_do_it);

a.cpp:7:58: warning: overflow in implicit constant conversion [-Woverflow]

#define static_warning(x, str) example< ((x)? 0:(1<<30)) > str(example<0>::int_x<__LINE__>)

a.cpp:13:1: note: in expansion of macro 『static_warning』

static_warning(false, do_not_do_it);

注意提示的內容:「overflow in implicit constant conversion」 也是滿足題主的需求的。所以題主你想要什麼型別的錯誤提示,就製造這種常量模板引數的轉換就行了(題主請練習一下如何產生無符號數對有符號數賦值的警告)。

do_not_do_it填你想要自定義的錯誤資訊吧。

Compiler Error C2975 居然 vs說__LINE__不是編譯期常量,, 那就在vs上把__LINE__刪掉吧。。

2樓:大妖精

實際上這種行為是不安全的->理應拋error的。你可以完全拒絕這種直接賦值的寫法(拋error)並加乙個force_truncate函式用來強制截斷。

3樓:

編譯期輸出..基本上得靠編譯器吧

這裡有個類似的現成方案,改gcc編譯期輸出https://

也許metaclass未來會有compiler.warning不過現在proposal只有compiler.error()

C 如何實現優先佇列?

原生的Priority Queue已經被merge了 API 描述如下,感覺上符合大部分的需求了,應該是不是執行緒安全的,需要注意 namespace System.Collections.Generic public class PriorityQueue NB does not implemen...

c語言裡malloc的最優實現方式是什麼?

壓根不關心malloc critical path malloc free,非critical的你加鎖我都無所謂。其他情況我用go,python,nodejs. vibiu 讀過redis的原始碼會發現它自己實現了乙個zmalloc,允許使用google的tcmalloc和facebook的jema...

C 如何實現自動呼叫建構函式?

夏洋 如果你用C 11的話,直接這麼寫就行了 class UserClass Base 甚至你想只寫成一句 DefValues i,j,k 也是有辦法的。例如 define FIRST a,a define SECOND a,b,b define EMPTY define DEFER1 m m EM...