我写了一个元函数来检索成员函数的第一个参数的类型,它当然接收一个或多个参数。我写的代码如下:
template <typename...> struct parameter;
template < typename O, typename A, typename R, typename... Args>
struct parameter <R (O::*)(A, Args...) > {
using first_param = A;
};
我使用这个元函数如下:
using mem_fn = void(mem_type::*)(std::vector<int>);
using f_pm = parameter<mem_fn>::first_param;
它编译并工作。但是当我上课时:
struct mem_type{
void update(std::vector<int>) {
}
};
并按如下方式使用我的元函数:
using mem_fn = decltype(mem_type::update);
using f_pm = parameter<mem_fn>::first_param;
代码无法编译,visual studio 2013 给出:错误 C2027:使用未定义类型 parameter<mem_fn>
.
有谁知道这个错误的原因吗?
最佳答案
首先,id-expression 命名一个非静态成员函数(mem_type::update
在这种情况下)不能用作未评估的操作数(例如decltype
的操作数)。 §5.1.1 [expr.prim.general]/p13(省略脚注):
An id-expression that denotes a non-static data member or non-static member function of a class can only be used:
- as part of a class member access (5.2.5) in which the object expression refers to the member’s class or a class derived from that class, or
- to form a pointer to member (5.3.1), or
- if that id-expression denotes a non-static data member and it appears in an unevaluated operand.
§7.1.6.2 [dcl.type.simple]/p4:
The operand of the
decltype
specifier is an unevaluated operand (Clause 5).
即使 update
是一个常规函数,decltype
也会生成函数类型而不是函数指针类型,并且您的特化匹配一个指向成员的指针-函数类型。
您需要使用 &
创建指向成员函数的指针 - 即 decltype(&mem_type::update)
。
关于c++ - C++11成员函数第一个参数的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27159187/