What is an lvalue reference to function?
In §14.1.4, the new C++0x standard describes the non-types allowed as template parameters.
4) A non-type template-parameter shall have one of the following (optionally cv-qualified) types:
- integral or enumeration type,
- pointer开发者_StackOverflow to object or pointer to function,
- lvalue reference to object or lvalue reference to function,
- pointer to member.
What is an "lvalue reference to function"? What does it look like in a template paramemter list. How is it used?
I want something like this:
//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;
}
Your func_t
is of type pointer to function; you can also declare a type that is a reference to a function:
typedef int (&func_t)(int, int);
Then your main()
would look like so:
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;
}
精彩评论