【问题标题】:C++ Templates with pointer to member function by signature and type具有通过签名和类型指向成员函数的指针的 C++ 模板
【发布时间】:2015-05-09 11:53:58
【问题描述】:

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

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

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

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

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

【问题讨论】:

  • @Daniel Frey 是的。我知道一切正常。我问:为什么这样有效?我在哪里可以在 C++ 标准中读到这样的事情是正确的。

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


【解决方案1】:

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

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

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

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

[temp.param]/3 标识符不跟随省略号的类型参数定义 它的标识符是 typedef-name

所以你的模板定义有两个参数T 和签名。在模板体中使用signature时,因此相当于typedef

typedef void signature(float, int);

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

[dcl.fct]/12 函数类型的 typedef 可用于声明函数,但应 不能用于定义函数

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

[dcl.mptr]/1T D 的声明中,D 的格式为

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

nested-name-specifier 表示一个类,而 声明 T D1 中的标识符是 derived-declarator-type-list T,则D的标识符的类型为 derived-declarator-type-list cv-qualifier-seq 指向类型为 T 的嵌套名称说明符的成员的指针

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

这解释了编译器将为示例推断出哪些类型

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

【讨论】:

    猜你喜欢
    • 2011-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多