指向模板化函数的函数指针

use*_*733 5 c++ templates template-meta-programming

我有两个模板化函数签名。这里 T 可以是 int 或 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)
{
 ...
}
Run Code Online (Sandbox Code Playgroud)

现在根据方向,我想调用 f2p 或 p2f。我想创建一个指向 f2p 或 p2f 的函数指针。如何创建指向模板函数的函数指针?我想达到如下效果:

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);
}
Run Code Online (Sandbox Code Playgroud)

我尝试类似的方法,但出现编译错误:

Box<T> (*p)(Box<T>, Point<T>, Orientation) = dir ? fc2p<T> : p2fc<T>
Run Code Online (Sandbox Code Playgroud)

Bar*_*rry 3

我尝试类似的方法,但出现编译错误:

Box<T> (*p)(Box<T>, Point<T>, Orientation) = dir ? f2p<T> : p2f<T>
Run Code Online (Sandbox Code Playgroud)

仔细查看您的函数所采用的参数:

template <typename T>
Box<T> f2p(Box<T> const& box, Point<T> const& pt, Orientation o)
                 ^^^^^^^^             ^^^^^^^^
Run Code Online (Sandbox Code Playgroud)

所有参数必须完全匹配。在这种情况下:

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

或者,简单地说:

auto p = dir ? f2p<T> : p2f<T>;
Run Code Online (Sandbox Code Playgroud)