我知道我可以这样做:
template<typename T, typename Ret, typename A1, typename A2, Ret(T::*F)(A1, A2)>
class C{}
但正如你所看到的A1
and A2
有点丑。事实上我不知道参数的数量。听起来像是可变参数模板的工作。不幸的是我不能这样做:
// doesn't work - parameter pack must appear at the end of the template parameter list
template<typename T, typename Ret, typename... Args, Ret(T::*F)(Args...)>
class C{}
也不是这个:
模板
C级;
// doesn't work - wrong syntax
template<typename T, typename F, typename Ret, typename... Args>
class Delegate2<Ret(T::*F)(Args...)>{}
我想要的太多了吗?
您可以执行以下操作:
template<typename T, T> struct C;
template<typename T, typename R, typename ...Args, R (T::*F)(Args...)>
struct C<R (T::*)(Args...), F> {
R operator()(T &obj, Args &&... args) {
return (obj.*F)(std::forward<Args>(args)...);
}
};
然后在你的程序中:
struct A {
int foo(int i) { return i; }
};
int main() {
C<int(A::*)(int), &A::foo> c;
A a;
std::cout << c(a, 42) << std::endl;
}
现场演示 http://coliru.stacked-crooked.com/a/708c7b258efaae9f
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)