5

I have two templated function signatures. Here T can be either int or double.

template <typename T>
Box<T> f2p(Box<T> const& box, Point<T> const& pt, Orientation o)
{
 ...
}

template <typename T>
Box<T> p2f(Box<T> const& box, Point<T> const& pt, Orientation o)
{
 ...
}

Now depending upon direction, I want to call either f2p or p2f. I want to create a function pointer that points to either f2p or p2f. How do I create a function pointer to a templated function? I want to achieve the following effect:

typename <template T>
Box<T> do_transformation(Box<T> const& box, ..., int dir = 0)
{
   function pointer p = dir ? pointer to f2p : pointer to p2f

   return p<T>(box);
}

I try something like this but I get compile errors:

Box<T> (*p)(Box<T>, Point<T>, Orientation) = dir ? fc2p<T> : p2fc<T>

3 Answers 3

4

I try something like this but I get compile errors:

Box<T> (*p)(Box<T>, Point<T>, Orientation) = dir ? f2p<T> : p2f<T>

Take a careful look at the arguments your functions take:

template <typename T>
Box<T> f2p(Box<T> const& box, Point<T> const& pt, Orientation o)
                 ^^^^^^^^             ^^^^^^^^

All the arguments have to match exactly. In this case:

Box<T> (*p)(Box<T> const&, Point<T> const&, Orientation) = dir ? f2p<T> : p2f<T>;

Or, simply:

auto p = dir ? f2p<T> : p2f<T>;
Sign up to request clarification or add additional context in comments.

1 Comment

Can't believe it didn't even occur to me to use auto.
3

You can't have a pointer to a function template, but you can have a pointer to a specific instantiation of a function template.

Box<T>(*p)(Box<T> const&, Point<T> const&, Orientation);
p = dir ? &f2p<T> : &p2f<T>;

Comments

0

Unless you need pointer for something else, you can use:

typename <template T>
Box<T> do_transformation(Box<T> const& box, ..., int dir = 0)
{
   return (dir ? f2p(box, ...) : p2f(box, ...));
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.