具有按签名和类型指向成员函数的指针的 C++ 模板

标签 c++ templates pointers function-pointers language-lawyer

下面的代码工作正常,但我无法根据 C++ 标准的哪些点确定它应该有效。

template< class C, class signature >
void f(signature C::*ptr) { }

C = Asignature = void(float, int) 时,函数 f 将是

void f(void(A::*ptr)(float, int))

基于标准的哪些部分,模板是否适用于后者?

最佳答案

最好一一完成。为了避免歧义,我将在示例中使用不同的模板参数名称

template<class C, class signature> void f(signature C::*ptr) {}

所有引用均指 C++14 标准的最新工作草案。

首先我们需要了解模板参数是如何处理的。

[temp.param]/3 A type-parameter whose identifier does not follow an ellipsis defines its identifier to be a typedef-name

因此您的模板定义有两个参数 T 和签名。当在模板主体中使用 signature 时,它因此等同于 typedef

typedef void signature(float, int);

此 typedef 可用于声明函数指针参数,如您的示例所示:

[dcl.fct]/12 A typedef of function type may be used to declare a function but shall not be used to define a function

在模板函数的参数中,你写了signature T::*ptr,让我们看看标准对成员指针是怎么说的:

[dcl.mptr]/1 In a declaration T D where D has the form

nested-name-specifier * attribute-specifier-seq_opt cv-qualifier-seq_opt D1

and the nested-name-specifier denotes a class, and the type of the identifier in the declaration T D1 is derived-declarator-type-list T, then the type of the identifier of D is derived-declarator-type-list cv-qualifier-seq pointer to member of class nested-name-specifier of type T.

在我们的例子中,Tsignature,函数typedef,DC::*ptr.

这解释了编译器将为该示例推导出什么类型

void f(void(A::*ptr)(float, int));

关于具有按签名和类型指向成员函数的指针的 C++ 模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30139580/

相关文章:

c++ - 是首先调用 init 部分函数还是构造函数?

c++ - 包含 MySQLStore.h 但 HAVE_MYSQL 未定义错误(quickfix VS2015 c++)

c++ - 具有基于身份的相等性的有序关联容器

c++ - 使用 CRTP 创建特征矩阵

git - 如何查看从我的存储库模板 (GitHub) 创建的存储库数量

c - 如何做一个矩阵指针数组?

C:使用=(等于)复制指针数据

ios - 按下按钮后记录时数据 (char*) 出现损坏

c++ - 如何在 GDB 中打印 C++ vector 的元素?

c++ - 面向对象的编程风格和指向指针的指针