常量函数指针类型作为模板参数的"invalid use of incomplete type"
"invalid use of incomplete type" for const function pointer type as template argument
考虑以下用于函子包装的简化代码:
#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; // ^^^^^
};
相关文章:
- 如何处理 c++ 中类实现中的"invalid use of non-static data member"?
- C++ "error: invalid use of void expression"
- 收到错误"invalid use of non-static data member 'stu::n' "
- C++ "Invalid use of 'this' in non-member function" ,
- 继承类时"invalid use of incomplete type ‘class tree_node_t’"
- 出现这种错误的原因是什么"invalid use of non-static data member "
- 模板类和'invalid use of incomplete type'错误
- "invalid use of incomplete type" .解决循环依赖关系
- 为什么我会得到"Invalid use of :: (scope resolution operator)?"
- 如何修复库中的"invalid use of non-static member function" 导入另一个库
- 在C++中传递对象会产生'invalid use of non-static member'错误
- 为什么当我尝试在类中创建数组时"invalid use of non-static data member"我会收到错误?
- 具有重载<<运算符的简单模板类失败,"Invalid use of template-id"
- C++ substr 方法 - "invalid use of ‘this’ in non-member function"
- C++错误:" 'class' does not name a type"和"invalid use of incomplete type ‘struct ...' "
- 访问父类的成员"Invalid use of non-static data member" C++
- "invalid use of non static member function" 这是什么?
- 使用 getline 和层次结构时"invalid use of ‘struct main()"
- C++类模板和嵌套结构。 "Invalid use of non-static data member..."
- 多重继承错误'invalid use of incomplete type'