我有一个C++11的例子,其中我有一个名为
call
的函数,它使用可变参数模板来接受并调用通用类方法。#include <utility>
template <typename T, typename R, typename... Args>
R call(R (T::*fn)(Args...), T *t, Args&&... args) {
return ((*t).*fn)(std::forward<Args>(args)...);
}
class Calculator {
public:
int add(const int& a, const int& b) {
return a + b;
}
};
int main() {
Calculator *calculator = new Calculator();
int* a = new int(2);
int* b = new int(4);
// compiles
int res1 = calculator->add(*a, *b);
// does not compile!
int res2 = call<Calculator>(&Calculator::add,calculator, *a, *b);
return 0;
}
如代码中所述,当函数接受 const int
时,我无法传递 int
,但在类似于方向方法调用的情况下,我可以。 我收到以下编译错误:
error: no matching function for call to ‘call(int (Calculator::*)(const int&, const int&), Calculator*&, int&, int&)’
int res2 = call<Calculator>(&Calculator::add,calculator, *a, *b);
^
inconsistent parameter pack deduction with ‘const int&’ and ‘int&’
int res2 = call<Calculator>(&Calculator::add,calculator, *a, *b);
^
使用C++变长模板会比普通执行更加强制进行类型检查吗?我正在使用带有C++ 11的g++ 4.8.1。
template <typename F, typename T, typename... Args> auto call(F f, T *t, Args&&... args) { return (t->*f)(std::forward<Args>(args)...); }
- chrisF
,我应该传递什么参数? - jeffreyveon