常量函数指针类型作为模板参数的"invalid use of incomplete type"

"invalid use of incomplete type" for const function pointer type as template argument

本文关键字:invalid use of type incomplete 参数 指针 函数 类型 常量      更新时间:2023-10-16

考虑以下用于函子包装的简化代码:

#include <iostream>
#include <utility> // std::forward
template <class F>
struct return_type;
template <class R, class C, class... A>
struct return_type <R (C::*)(A...)> {
  typedef R type;
};
// ----------------------
template <class FunctorType, typename FunctionPointerType>
class functor_wrapper {
public:
    FunctorType* f;
    FunctionPointerType p;
    functor_wrapper (FunctionPointerType pp) : p(pp) { f = new FunctorType; }
    template <class... A>
    typename return_type<FunctionPointerType>::type  operator() (A && ... args) {
        return ( (f->*p) (std::forward<A>(args)...) );
    }
};
// ----------------------
class my_less {
public:
    bool non_const_mem (const int& x, const int& y) {return x<y;}
    bool const_mem (const int& x, const int& y) const {return x<y;}
};
// ----------------------
int main(int argc, char *argv[])
{
    // functor_wrapper <my_less, bool (my_less::*)(const int&, const int&)>  foo(&my_less::non_const_mem); // OK!!
    functor_wrapper <my_less, bool (my_less::*)(const int&, const int&) const>  foo(&my_less::const_mem); // ERROR!!
                                                                    //  ^^^^
    std::cout << "is 2<5? " << (foo(2,5)?"yes":"no") << std::endl;
}

在'foo'的声明中,如果我使用常量成员函数,我得到编译错误" invalid use of incomplete type ‘struct return_type<bool (my_less::*)(const int&, const int&)const>’ "。但是,如果它是非常量成员函数,则可以正常编译和运行。当成员函数是常量类型时,我不明白"不完整类型"在此代码中的位置,以及我可以做些什么来使其适用于常量成员函数?

您缺少一个合适的合格模板专门化,就像这样:

template <class R, class C, class... A>
struct return_type <R (C::*)(A...) const> {
    typedef R type;             // ^^^^^
};