【问题标题】:C++ function wrapper of a function with a template argument带有模板参数的函数的 C++ 函数包装器
【发布时间】:2019-02-27 06:11:35
【问题描述】:

我正在尝试制作一个函数包装器,它接受一个带有 1 个模板参数的函数并在另一个头文件中使用它。基本上,主程序计算定义 my_function 的某些变量,用于在 CGAL 中定义“criteria.h”头文件。这是包含函数和函数包装器的“sizing_fun.h”:

template <typename Point_vec>
double my_function(double x, double y, Point_vec list_of_points)
{
  //use list_of_points
  return 4.0+(x*x+y*y);
}

template <typename FT, typename Point_2, typename Point_vec>
class FT_to_point_function_wrapper : public std::binary_function<Point_2, Point_vec, FT>
{
  typedef FT (*Implicit_function)(FT, FT, FT);
  Implicit_function function;
 public:
  FT_to_point_function_wrapper(Implicit_function f) : function(f) {}
  FT operator()(Point_2 p, Point_vec list) const { return function(p.x(), p.y(), std::forward<Point_vec>(list)); } //error line
};

在“criteria.h”中,我使用 my_func 作为上面定义的函数包装器。 pcc 是 Point_2 参数,my_list 是 Point_vec 参数。

double local_squared_size_bound = my_func(pcc,my_list);

我去错误信息:

sizing_fun.h:17: error: cannot convert 'std::vector<CGAL::Point_2<CGAL::Epick>, std::allocator<CGAL::Point_2<CGAL::Epick> > >' to 'double' in argument passing

所以看起来 Point_vec 类型没有正确传递。

我意识到这篇文章: C++ function call wrapper with function as template argument 但我认为它不同,因为它的函数没有模板参数。

【问题讨论】:

  • 请发布您的完整代码。

标签: c++ templates cgal


【解决方案1】:

typedef FT (*Implicit_function)(FT, FT, FT);

您声明该函数对所有 3 个参数都接受相同的类型,并且还返回相同的类型。

应该是typedef FT (*Implicit_function)(FT, FT, Point_vec);

修复Implicit_function的签名,你的问题应该就没有了。

如果这至少是 C++11,您还应该更喜欢 std::function 而不是原始函数指针,以便可以接受带有绑定/捕获的函数或 lambda。

FT_to_point_function_wrapper::function 应声明为const,因为它仅由构造函数中的初始化列表设置。如果使用 C++11,您还可以将 FT_to_point_function_wrapper::FT_to_point_function_wrapper 声明为 constexpr

FT_to_point_function_wrapper::operator() 也应声明为 const

【讨论】:

    猜你喜欢
    • 2016-07-29
    • 1970-01-01
    • 2019-10-20
    • 2020-10-26
    • 1970-01-01
    • 1970-01-01
    • 2013-02-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多