【发布时间】:2019-05-28 19:51:17
【问题描述】:
我有以下类型定义:
template<typename G, typename T, typename R>
using my_func_type = typename R(T::*)(G, int) const;
这是一个我经常使用的成员函数,所以我正在尝试制作不同的包装器。前提是我想要一个通过通用函数调用实现这些函数的对象,这样我就可以将它们以不同的方式组合起来(目前我使用直接将调用包装为 lambdas 的方式)。
但是,另一种方法是将该函数作为非类型模板参数传递(与 lambda 解决方案相比,这提高了我的性能,因为我一直在评估它),即。
template<typename G, typename T, typename R, my_func_type<G, T, R> f>
struct MyWrapper
{
MyWrapper(G g, T t) : g{ g }, t{ t } {}
auto eval(int n) const
{
return (t.*f)(g, n);
}
protected:
G g;
T t;
};
int main()
{
AnObject g;
TheCallingObject t;
auto f = &TheCallingObject::callit;
MyWrapper<AnObject, TheCallingObject, double, f> wrap(g, t)
}
但这似乎有点多余,那么模板参数是否可以从f推导出来?
我找到的中途解决方案是:
template<auto f, typename G, typename T>
struct MyWrapper
{
OpFuncDerivative(G g, T t) : g{ g }, t{ t } {}
auto eval(int n) const
{
return (t.*f)(g, n);
}
protected:
G g;
T t;
};
int main()
{
AnObject g;
TheCallingObject t;
auto f = &TheCallingObject::callit;
// it won't automatically deduce AnObject and TheCallingObject
// through the parameters to the constructor though!
MyWrapper<f, AnObject, TheCallingObject> wrap(g, t)
}
【问题讨论】:
标签: c++ visual-c++ template-argument-deduction