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 founderror 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 pointererror: 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()函数的方法:推导返回的类型(因此避免autodecltype()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推导出来的。

10-08 08:28
查看更多