gpt4 book ai didi

C++ is_member_pointer 实现

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:53:57 24 4
gpt4 key购买 nike

在c++标准库中,is_member_pointer实现为

  template<typename _Tp>
struct __is_member_pointer_helper
: public false_type { };

template<typename _Tp, typename _Cp>
struct __is_member_pointer_helper<_Tp _Cp::*>
: public true_type { };

/// is_member_pointer
template<typename _Tp>
struct is_member_pointer
: public __is_member_pointer_helper<typename remove_cv<_Tp>::type>::type
{ };

有人可以解释一下 _Cp 是如何推导出来的吗?它像魔术一样工作。

最佳答案

指向成员的指针的类型是Type Class::*,其中Type 是指向的对象类型或函数类型。例如,如果您为模板提供 int C::*,编译器可以通过检查指向成员的指针的类型并看到类类型是 来简单地推断出类类型C。它还会以相同的方式将指向的类型推断为 int。它的工作方式与我们人类的工作方式非常相似。一般来说,我们称这种技术为pattern matching ,您可能熟悉 regular expressions .

正式地:

[temp.deduct.type]/3.2:

A pointer-to-member type includes the type of the class object pointed to and the type of the member pointed to.

[temp.deduct.type]/8 :

A template type argument T, a template template argument TT or a template non-type argument i can be deduced if P and A have one of the following forms:

  • [snip]
  • T T::*
  • [snip]

根据[temp.deduct.type]/1 :

Template arguments can be deduced in several different contexts, but in each case a type that is specified in terms of template parameters (call it P) is compared with an actual type (call it A), and an attempt is made to find template argument values (a type for a type parameter, a value for a non-type parameter, or a template for a template parameter) that will make P, after substitution of the deduced values (call it the deduced A), compatible with A.

关于C++ is_member_pointer 实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55185873/

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