2010-07-16 80 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