通常,生成警告似乎是一種好方法(警告而不是錯誤,因此您可以在一次編譯運行中記錄多個事件)。這是我一直在使用一個功能,它允許傳入的值並獲取其類型的印刷,或傳遞一個類型作爲模板參數:
template <typename T>
inline void debug_type(const T&) __attribute__((deprecated));
template <typename T>
inline void debug_type(const T&) { }
template <typename T>
inline void debug_type() __attribute__((deprecated));
template <typename T>
inline void debug_type() { }
您可以使用它像這樣:
debug_type(1); // Pass a value, let the compiler deduce its type
debug_type<char>(); // Pass a type explicitly
這導致警告這樣的:
foo.cpp:73:17: warning: 'void debug_type(const T&) [with T = int]' is deprecated (declared at /tmp/arduino_build_static/sketch/Num.h:13) [-Wdeprecated-declarations]
debug_type(1);
^
foo.cpp:74:22: warning: 'void debug_type() [with T = char]' is deprecated (declared at /tmp/arduino_build_static/sketch/Num.h:19) [-Wdeprecated-declarations]
debug_type<char>();
的錯誤消息的T = int
部分示出的類型(當然其可以是更復雜的模板類型,這僅僅是一個例子) 。
這個警告相對於其他地方提出的未使用變量警告的一個特殊優點是錯誤位置是調用debug_type
的地方,而不是它的實現,所以錯誤中顯示的代碼片段顯示了正在打印類型的表達式(當你想一次打印幾個不同的東西時,這可能很方便)。
我懷疑這一點。有了一些幻想,你可以將一個或另一個警告修改爲特定的模板診斷。 – hirschhornsalz 2009-12-01 13:27:43
static_assert可以發出消息。這是一個C++ 0x功能,可用於VC++ 10。但是,不可能通過一個完整的部分來推斷。 – 2009-12-01 13:34:04
BOOST_MPL_ASSERT_MSG可以在C++(非0x) – KitsuneYMG 2009-12-01 14:06:16