【发布时间】:2019-01-12 02:18:43
【问题描述】:
我正在编写一个以仿函数为参数的函数。仿函数的调用运算符的参数是模板化的。我正在尝试做的一个非常简化的版本是:
#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;
}
基本上,我能看出两者之间的唯一区别是一个是模板化的,另一个不是。是因为第一个sn-p中的step函数只是一个模板,没有实例化还是别的什么?
【问题讨论】:
标签: c++11 templates c++14 functor template-argument-deduction