2014-02-28 71 views
3

我寫後續碼:初始化通過在C++ lambda表達式

static int count = []()->int 
        { 
         int count = 0; 

         for(int i = 0; i < categories.size(); ++i) 
         { 
          if(!categories[i].isCategory()) 
          { 
           count++; 
          } 
         } 

         return count; 
        }; 

,並得到誤差:error: cannot convert '__lambda0' to 'int' in initialization

確實我的代碼片段的含義是指定__lambda0static int count而不是返回內部計數?

+1

是的,你要指定的拉姆達(功能),而不是它的評價。你需要實際調用lambda。 – heinrichj

回答

4

你不叫它!確保你這樣做:

static int count = []()->int 
        { 
         int count = 0; 

         for(int i = 0; i < categories.size(); ++i) 
         { 
          if(!categories[i].isCategory()) 
          { 
           count++; 
          } 
         } 

         return count; 
        }(); 
       // ^^ THIS THIS THIS THIS 

但是,恕我直言,你最好在這不使用拉姆達。並且在你的代碼的其他部分使用它的情況下,將它放在獨立的(不是lambda)函數中。

+0

擊敗我7秒! – Potatoswatter

+0

@Patatoswatter擊敗你7秒! :) –

+0

我認爲這是一個有效的用例。它可能是一個靜態本地,lambda可能取決於其他本地人。 (但這個例子沒有顯示任何東西被捕獲。) – Potatoswatter

1

does the meaning of my code fragment is assign the __lambda0 to static int count instead of return the inner count?

沒錯。要調用lambda,只需在末尾添加()

    … 
       }();