我知道我可以做到:
template<typename T, typename Ret, typename A1, typename A2, Ret(T::*F)(A1, A2)>
class C{}
但如您所见,A1
和 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;
}
关于c++ - 模板参数 - 带有可变参数的函数指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36549237/