Mar*_* Ba 12 c++ boost boost-bind function-templates
是否可以使用(boost)bind将参数绑定到函数模板?
// Define a template function (just a silly example)
template<typename ARG1, typename ARG2>
ARG1 FCall2Templ(ARG1 arg1, ARG2 arg2)
{
return arg1 + arg2;
}
// try to bind this template function (and call it)
...
boost::bind(FCall2Templ<int, int>, 42, 56)(); // This works
boost::bind(FCall2Templ, 42, 56)(); // This emits 5 pages of error messages on VS2005
// beginning with: error C2780:
// 'boost::_bi::bind_t<_bi::dm_result<MT::* ,A1>::type,boost::_mfi::dm<M,T>,_bi::list_av_1<A1>::type>
// boost::bind(M T::* ,A1)' : expects 2 arguments - 3 provided
boost::bind<int>(FCall2Templ, 42, 56)(); // error C2665: 'boost::bind' : none of the 2 overloads could convert all the argument types
Run Code Online (Sandbox Code Playgroud)
想法?
Dav*_*e S 18
我不这么认为,只是因为boost::bind在这种情况下是寻找函数指针,而不是函数模板.传入时FCall2Templ<int, int>,编译器实例化该函数,并将其作为函数指针传递.
但是,您可以使用仿函数执行以下操作
struct FCall3Templ {
template<typename ARG1, typename ARG2>
ARG1 operator()(ARG1 arg1, ARG2 arg2) {
return arg1+arg2;
}
};
int main() {
boost::bind<int>(FCall3Templ(), 45, 56)();
boost::bind<double>(FCall3Templ(), 45.0, 56.0)();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
您必须指定返回类型,因为返回类型与输入相关联.如果返回没有变化,那么您只需添加typedef T result_type到模板,以便绑定可以确定结果是什么