简体   繁体   中英

Function pointer to templated function

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>

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

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

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, ...));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM