c++ - C++11成员函数第一个参数的类型

标签 c++ templates c++11 template-meta-programming

我写了一个元函数来检索成员函数的第一个参数的类型,它当然接收一个或多个参数。我写的代码如下:

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/

相关文章:

c++ - 预编译头文件,重新包含文件和智能感知

c++ - 减少模板标题的大小

c++ - 重新学习现代 C++ 资源?

c++ - 使用 C++ 模板编译类成员变量?

c++ - CRTP:为什么获取派生类的嵌套类型和嵌套方法之间存在差异?

c++ - 线程上下文的静态存储对象优化

没有.cpp文件没有内联函数的c++类?

c++11 - 为什么 `vector<int> v{{5,6}};` 有效?我以为只允许一对 {}?

c++ - 调用库时崩溃

c++ - 在 C++ 中使用 ASM