将带有模板化参数的函子传递给模板函数

时间:2019-01-12 02:18:43

标签: c++11 templates c++14 functor template-deduction

我正在编写一个以函子为参数的函数。仿函数的call运算符的参数是模板化的。我正在尝试做的一个非常简化的版本是:

#include <iostream>
#include <functional>
#include <array>

template <const size_t N>
using CVec = std::array<double,N>;

template<const size_t N>
using ode_fun = std::function<CVec<N>(const CVec<N>&)>;

template<const size_t N>
void step( const CVec<N>& x, ode_fun<N> sys)
{
  sys(x);
}

struct foo_t
{
  CVec<2>  operator()( const CVec<2>& x_in)
  {
    CVec<2> xdot;

    std::cout << "x_in: [" << x_in[0] << ", " << x_in[1] << "]\n";

    return xdot;
  }
  CVec<2> x;
};

int main()
{
  foo_t foo;
  foo.x[0] = -.5;
  foo.x[1] = 1.0f;

  CVec<2> x;
  x[0] = 12.0;
  x[1] = 23.2;

  step(x, foo);
}

但是在编译时,出现此错误:

temp_arg_subs_fail.cpp: In function ‘int main()’:
temp_arg_subs_fail.cpp:42:14: error: no matching function for call to ‘step(CVec<2>&, foo_t&)’
   step(x, foo);
              ^
temp_arg_subs_fail.cpp:12:6: note: candidate: template<long unsigned int N> void step(CVec<N>&, ode_fun<N>)
 void step( const CVec<N>& x, ode_fun<N> sys)
      ^~~~
temp_arg_subs_fail.cpp:12:6: note:   template argument deduction/substitution failed:
temp_arg_subs_fail.cpp:42:14: note:   ‘foo_t’ is not derived from ‘std::function<std::array<double, N>(const std::array<double, N>&)>’
   step(x, foo);
              ^

但这可行:

#include <functional>
#include <iostream>

using my_fn = std::function<int(int, int)>;

void summer(int x, int y, my_fn fn)
{
  std::cout << "summer: " << fn(x,y) << std::endl;
}

struct foo_t
{
  int operator()(int x, int y)
  {
    return x + y + z;
  }    
  int z = 0;    
};

int main ()
{    
  foo_t foo;
  foo.z = 5;    

  summer(3,4,foo);

  return 0;
}

基本上,我可以分辨出两者之间的唯一区别是一个是模板化的,而另一个则不是。是因为第一个代码段中的step函数只是一个模板而不是实例化的吗?

1 个答案:

答案 0 :(得分:1)

问题在于step()需要一个ode_fun<N>对象作为第二个参数(即std::function<std::array<double, N>(std::array<double, N> const &)>),并推论出N

但是,如果您传递foo,那是一个foo_t对象,可以将其转换为ode_fun<2>,但是(这是重点)不是 ode_fun<2>对象,编译器无法推导N值。

您可以通过两种明显的方式解决问题。

(1)将ode_fun<2>对象传递给step()

ode_fun<2>  foo2 { foo };

step(x, foo2);

(2)或在F中推导简单类型step()(作为“函数”),因此所有函数都是可推论的

template<const size_t N, typename F>
void step( const CVec<N>& x, F sys)
{
  sys(x);
}
  

是因为第一个片段中的step函数只是一个模板,而没有实例化吗?

完全正确。

在您的非模板示例中,summer()收到std::function<int(int, int)>

没有什么可推论的,因此将不是foo_t但可以转换为std::function<int(int, int)>的{​​{1}}对象传递给它,编译器将foo转换为std::function<int(int, int)>

相关问题