2011-06-01 60 views
2

我試圖建立一個小例子:仿函數調用(其他字符)

struct Functor 
{ 
    void operator()(int& a) 
    { 
     a += 1; 
    } 
    void other(int& a) 
    { 
     a += 2; 
    } 
}; 

template <typename foo> 
class Class 
{ 
    public: 
     void function() 
     { 
      int a = 10; 
      foo()(a); 
      std::cout << a << std::endl; 
     } 
}; 

int main() 
{ 
    Class<Functor> c; 
    c.function(); 
} 

我這個問題:爲什麼是它甚至可能呼籲純粹型操作者沒有對象?我如何以與我所稱的operator()相同的方式調用函數other

+0

在哪裏 「純型」? – 2011-06-01 09:12:06

回答

8

你不是在純粹的類型上調用它。 foo()調用構造函數,並計算臨時對象foo,然後調用operator()

要與「正常」的成員函數做相當的,只是做:

foo().other(a); 
+0

這意味着每個調用都會有一個對象在堆棧上分配? – DyingSoul 2011-06-01 09:09:14

+0

@DyingSoul:如果你這樣做,那麼是的!雖然編譯器可以自由優化,但它喜歡。 – 2011-06-01 09:10:03

+4

@DyingSoul:是和否,因爲你的結構是空的,而且由於這些方法是內聯的,所以編譯器可能會簡單地在「in place」方法中執行代碼(相當於替換'foo()(a)如果你的方法不是內聯的(無論什麼原因),那麼它將不得不在棧上保留一個字節(至少),因爲有效地址需要傳遞給方法( 'this'),並且它不知道你不需要它,實際上。 – 2011-06-01 09:33:03

3

你是不是「調用[和]上的純型運營商無一物」。語法foo()(a)正在創建類型foo(這是foo()部分)的臨時文件,然後以a作爲參數(該部分爲(a)部分),在該對象上調用operator()

2

純類型例如:

struct Functor 
{ 
    void operator()(int& a) 
    { 
     a += 1; 
    } 
    void other(int& a) 
    { 
     a += 2; 
    } 
    static void one_more(int& a) 
    { 
     a += 3; 
    } 
}; 

template <typename foo> 
class Class 
{ 
    public: 
     void function() 
     { 
      int a = 10; 
      foo()(a); 
      foo().other(a); 
      foo::one_more(a); 
      std::cout << a << std::endl; 
     } 
}; 

int main() 
{ 
    Class<Functor> c; 
    c.function(); 
} 
+0

調用靜態函數更有效率,因爲我們不需要在堆棧上創建一個實例,對嗎? – DyingSoul 2011-06-01 09:21:05

+0

而編譯器可以內聯靜態函數,因爲編譯時會解決這個問題嗎? – DyingSoul 2011-06-01 09:21:43

+3

@DyingSoul:在這種情況下,所有這三個可能會變成相同的機器代碼,構造函數沒有可觀察的副作用,所以編譯器可以完全優化它。 – 2011-06-01 09:27:05