gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:34:13 25 4
gpt4 key购买 nike

下面的代码工作正常,但我无法根据 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com