[英]Dummy debug class stuck on std::endl overload
我以為我要用這樣的東西做一個快速而又臟的__DEBUG
啟用跟蹤:
#ifdef __DEBUG
# define dbg std::cout
# define err std::cerr
#else
#include <iostream>
class dummy_cout
{
private:
public:
dummy_cout & operator << ( auto &obj )
{ return *this; }
dummy_cout & operator << ( std::result_of< decltype( &std::endl ) >::type &obj )
{ return *this; }
};
# define dbg dummy_cout()
# define err dummy_cout()
#endif
int main( int argc, char *argv[] )
{
dbg << "Bla, bla. bla..." << std::endl;
}
但它給了我:
cond_dbg.cpp:16:66: error: decltype cannot resolve address of overloaded function
dummy_cout & operator << ( std::result_of< decltype( &std::endl ) >::type &obj )
我也試過了decltype
, result_of
, ostream
等的六種變體,但我仍然沒有采取任何進一步措施。
這很簡單。 如果我編譯定義__DEBUG
的代碼,我會有cout
和cerr
。 如果我進行正常的編譯,我會有我的dummy_cout
,它只是做什么,但只允許我的代碼編譯而沒有變化和雜亂。
任何幫助將不勝感激。
你不能寫decltype(&std::endl)
因為std::endl
不是一個函數,它是一個函數模板 :
template< class CharT, class Traits >
std::basic_ostream<CharT, Traits>& endl( std::basic_ostream<CharT, Traits>& os );
因此,它沒有類型,因此要求它沒有意義。 而且,即使它有一個類型,后續result_of
包裝就沒有任何意義。
std::cout << std::endl
工作的原因是有一個重載接受特定類型的函數指針:
basic_ostream& operator<<(
std::basic_ios<CharT,Traits>& (*func)(std::basic_ios<CharT,Traits>&) );
此運算符不是函數模板(它是basic_ostream
的成員函數,它是類模板),因此重載解析在此觸發實例化endl
。
要實現這一點,您應該做同樣的事情:
dummy_cout& operator<<( std::ostream&(*p)(std::ostream&) );
或者為你的假型選擇一些合適的CharT
和Traits
:
dummy_cout& operator<<( std::basic_ostream<C,T>&(*p)(std::basic_ostream<C,T>& ) );
只是一張紙條。 這個聲明在任何C ++標准中都是錯誤的:
dummy_cout& operator<<(auto& obj);
Terse函數模板語法是Concepts TS的一個特性,它仍然是TS。 除非你使用 - fconcepts
,否則你需要寫:
template <class T>
dummy_cout& operator<<(T& obj);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.