1

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 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; } 

1 Answer 1

3

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; } 
Sign up to request clarification or add additional context in comments.

5 Comments

And what's forbidden is the new 'rvalue reference' which is part of the language support for move constructors (generalizing std::move). E.g. typedef int (&&func_t)(int, int); would not yield a type usable in a template.
What does the do_it() function look like? Can I use func_t just like a function name?
@Caspin: The rest of the code is exactly the same. The only thing I'd note is that you don't have to use * on Func_type (you don't have to use it with the function pointer either).
@Ben: Is it even possible to obtain an rvalue reference to a function?
Probably not. But even if you could, it wouldn't be valid in this context.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.