2013-04-26 102 views
0

是否可以定義一個接受如下表達式的宏:object.method()?我想製作一個宏,將該表達式改變爲...沒有任何東西(刪除它)。只用function()我會這樣做:#define function(沒有任何價值),但是有可能創建一個帶點的宏嗎?帶點的預處理器宏?

編輯:關於MooingDuck的評論:

object.Method("text", "other"); 

定義:

void Class::Method(std::string arg1, std::string arg2) 
{ 
#if 0 
    if (condition) 
    { 
     Method2(arg1, arg2); 
    } 
#endif 
} 

拆卸:

object.Method("text", "other"); 
00394396 mov   edi,5 
0039439B mov   eax,offset string "other" (396348h) 
003943A0 lea   esi,[ebp-4Ch] 
003943A3 mov   dword ptr [ebp-38h],0Fh 
003943AA mov   dword ptr [ebp-3Ch],ebx 
003943AD mov   byte ptr [ebp-4Ch],bl 
003943B0 call  std::basic_string<char,std::char_traits<char>,std::allocator<char> >::assign (393360h) 
003943B5 mov   dword ptr [ebp-4],1 
003943BC mov   edi,4 
003943C1 mov   eax,offset string "text" (396350h) 
003943C6 lea   esi,[ebp-30h] 
003943C9 mov   dword ptr [ebp-1Ch],0Fh 
003943D0 mov   dword ptr [ebp-20h],ebx 
003943D3 mov   byte ptr [ebp-30h],bl 
003943D6 call  std::basic_string<char,std::char_traits<char>,std::allocator<char> >::assign (393360h) 
003943DB mov   esi,10h 
003943E0 mov   dword ptr [ebp-4],0FFFFFFFFh 
003943E7 cmp   dword ptr [ebp-1Ch],esi 
003943EA jb   main+0B9h (3943F9h) 
003943EC mov   eax,dword ptr [ebp-30h] 
003943EF push  eax 
003943F0 call  dword ptr [__imp_operator delete (3960ECh)] 
003943F6 add   esp,4 
003943F9 mov   edi,0Fh 
003943FE mov   dword ptr [ebp-1Ch],edi 
00394401 mov   dword ptr [ebp-20h],ebx 
00394404 mov   byte ptr [ebp-30h],bl 
00394407 cmp   dword ptr [ebp-38h],esi 
0039440A jb   main+0D9h (394419h) 
0039440C mov   ecx,dword ptr [ebp-4Ch] 
0039440F push  ecx 
00394410 call  dword ptr [__imp_operator delete (3960ECh)] 
00394416 add   esp,4 
+0

對於這樣的事情,你可以使用'#ifdef' /'#endif'構造。對此使用宏幾乎肯定是一個壞主意(如果甚至可能的話)。你究竟想要解決什麼問題? – 2013-04-26 00:40:46

+1

宏名稱必須是標識符;它不能包含'.'字符。 – 2013-04-26 00:41:32

+0

對於*任何*名稱的方法?或者爲一組特定的命名方法? – 2013-04-26 00:49:54

回答

3

你的代碼是:

void Class::Method(const std::string& arg1, const std::string& arg2) 
{ 
#if 0 
    if (condition) 
    { 
     Method2(arg1, arg2); 
    } 
#endif 
} 

但問題是,當你調用此方法,字符串常量,它仍然是構建std::string對象,因爲他們建造的過程中可能有副作用。

我想我會試試這個,直到函數內部纔會進行轉換,因此編譯器也可以忽略std::string構造。

template<class arg1_t, class arg2_t> 
void Class::Method(const arg1_t& arg1, const arg2_t& arg2) 
{ 
#if 0 
    if (condition) 
    { 
     Method2(arg1, arg2); 
    } 
#endif 
} 
+0

工作,謝謝。我有不同的解決方案,但這個更好,因爲它只允許我的類的方法被忽略。但它仍然依賴編譯器優化(擺脫)方法的能力。但那是我不會避免的。或者我會嗎? – NPS 2013-04-26 22:36:21

+0

總有'#define方法(X,Y)方法',但我真的不建議這樣做。 – 2013-04-27 00:46:37

+0

爲什麼不實際? – NPS 2013-04-27 06:59:29

1

宏的名稱是一個標識符。沒有辦法。

不同的編譯器可能允許不同的字符到標識符中(如$),但它們都不允許.。在一天結束時,C預處理器被設計成一個「輕量級預處理器」,並不像其他更強大的預處理器一樣,在80年代中期存在,而不是用於幻想轉換。

雖然你可以做這樣的事情(不是真的推薦):

struct DoNothing 
{ 
    void method() { } 
}; 

DoNothing g_inst; 

#define object g_inst 

幾乎可以肯定的宏生成的代碼將被優化完全去除。這種方法對所有使用的名稱都很敏感。一切都應該明確提及。