2010-07-16 85 views
1

在§14.1.4中,新的C++ 0x標準將允許的非類型描述爲模板參數。什麼是函數的左值引用?

4)一種非型模板參數應具有下列(任選CV-合格)類型之一:

  • 整數或枚舉類型,
  • 指針對象或指針功能
  • 左值引用對象或左值對函數的引用,
  • 指向成員的指針。

什麼是「功能的左值引用」?它在模板參數列表中看起來像什麼。它是如何使用的?

我想是這樣的:

//pointer to function 
typedef int (*func_t)(int,int); 

int add(int lhs, int rhs) 
{ return lhs + rhs; } 

int sub(int lhs, int rhs) 
{ return lhs - rhs; } 

template< func_t Func_type > 
class Foo 
{ 
public: 
    Foo(int lhs, int rhs) : m_lhs(lhs), m_rhs(rhs) { } 

    int do_it() 
    { 
     // how would this be different with a reference? 
     return (*Func_type)(m_lhs,m_rhs); 
    } 
private: 
    int m_lhs; 
    int m_rhs; 
}; 

int main() 
{ 
    Foo<&add> adder(7,5); 
    Foo<&sub> subber(7,5); 

    std::cout << adder.do_it() << std::endl; 
    std::cout << subber.do_it() << std::endl; 
} 

回答

3

func_t的類型是函數指針的;你也可以聲明一個類型,它是一個函數的引用:

typedef int (&func_t)(int, int); 

然後你main()看起來像這樣:

int main() 
{ 
    Foo<add> adder(7,5); 
    Foo<sub> subber(7,5); 

    std::cout << adder.do_it() << std::endl; 
    std::cout << subber.do_it() << std::endl; 
} 
+0

,什麼是禁止的是新的「右值引用」,這是部分移動構造函數的語言支持(概括'std :: move')。例如。 'typedef int(&& func_t)(int,int);'不會產生可用於模板的類型。 – 2010-07-16 00:56:03

+0

'do_it()'函數是什麼樣的?我可以像函數名一樣使用func_t嗎? – 2010-07-16 00:58:39

+0

@Caspin:其餘代碼完全一樣。我唯一需要注意的是,你不需要在'Func_type'上使用''''(你不必在函數指針中使用它)。 – 2010-07-16 01:00:31