nik*_*ack 6 c++ variadic-templates c++11
我知道我可以这样做:
template<typename T, typename Ret, typename A1, typename A2, Ret(T::*F)(A1, A2)>
class C{}
Run Code Online (Sandbox Code Playgroud)
但是你可以看到这一点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{}
Run Code Online (Sandbox Code Playgroud)
这不是:
模板类C;
// doesn't work - wrong syntax
template<typename T, typename F, typename Ret, typename... Args>
class Delegate2<Ret(T::*F)(Args...)>{}
Run Code Online (Sandbox Code Playgroud)
我想要太多吗?
您可以执行以下操作:
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)...);
}
};
Run Code Online (Sandbox Code Playgroud)
然后在你的程序中:
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;
}
Run Code Online (Sandbox Code Playgroud)