tags:

views:

56

answers:

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;
}
+3  A: 

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;
}
James McNellis
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 (` would not yield a type usable in a template.
Ben Voigt
What does the `do_it()` function look like? Can I use func_t just like a function name?
caspin
@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).
James McNellis
@Ben: Is it even possible to obtain an rvalue reference to a function?
James McNellis
@James: Probably not. But even if you could, it wouldn't be valid in this context.
Ben Voigt