template<typename T, typename F, typename ...Args>
auto f(F h, Args&&... args) -> decltype(h(args...)) {
T* t = new T(); // Don't worry, my actual code doesn't do this
return (t->h)(args...);
}
struct G {
int g() {
return 5;
}
};
int main() {
int k = f<G>(&G::g);
}
微软的编译器说
error C2672: 'f': no matching overloaded function found
和error C2893: Failed to specialize function template 'unknown-type f(F,Args &&...)'
。Clang的编译器说
note: candidate template ignored: substitution failure [with T = G, F = int (G::*)(), Args = <>]: called object type 'int (G::*)()' is not a function or function pointer
和error: no matching function for call to 'f'
。我很确定
int (G::*)()
是一个函数指针...?我想念什么? (在添加返回类型之前,所有这些工作都很好。) 最佳答案
非完全正确:int (G::*)()
是指向非静态方法的指针。那不是完全一样的东西,需要稍微不同的语法来调用它。
所以,代替
return (t->h)(args...);
您应该添加一个
*
并按以下方式调用h()
return (t->*h)(args...);
// ........^ add this *
decltype()
也是错误的。如果您至少可以使用C++ 14,则可以避免使用它,而只需使用auto
作为返回类型template <typename T, typename F, typename ...Args>
auto f (F h, Args&&... args) {
T* t = new T();
return (t->*h)(args...);
}
否则,如果必须使用C++ 11,则可以包含
<utility>
并使用std::declval()
,如下所示template <typename T, typename F, typename ...Args>
auto f(F h, Args&&... args) -> decltype((std::declval<T*>()->*h)(args...)) {
T* t = new T(); // .................^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
return (t->*h)(args...);
}
但是还有另一种编写
f()
函数的方法:推导返回的类型(因此避免auto
,decltype()
和std::declval()
)以及h()
的参数您可以如下编写
f()
template<typename R, typename T, typename ... As1, typename ... As2>
R f(R(T::*h)(As1...), As2 && ... args) {
T* t = new T();
return (t->*h)(args...);
}
并且避免显式调用它的
G
类型int k = f(&G::g);
// .....^^^^^^^^ no more explicit <G> needed
因为
T
模板类型是从参数&G::g
推导出来的。