简体   繁体   English

将指向数据成员的指针作为非类型模板参数传递时推断类型和 class

[英]Inferring type and class when passing a pointer to data member as a non-type template argument

I need to pass a pointer to data member, its type and the class it's a member of, to a template struct.我需要将指向数据成员的指针、它的类型和它所属的 class 传递给模板结构。 The following works:以下作品:

template<typename T, typename Cls, T Cls::*member> struct Member {};
struct Struct { int x; };
Member<int, Struct, &Struct::x>

But it requires to explicitly mention the type (T: int) and the class (Cls: Struct).但它需要明确提及类型(T:int)和 class(Cls:Struct)。 That should be unnecessary.那应该是不必要的。 The compiler should be able to figure those two types out on its own.编译器应该能够自己找出这两种类型。

In fact it can inferm them if I pass the pointer to data member to a function:事实上,如果我将指向数据成员的指针传递给 function,它可以推断出它们:

template<typename T, typename Cls> void member( T Cls::*member ) {}
struct Struct { int x; };
member( &Struct::x );

Is it possible to pass a pointer to data member as a non-type template argument, while letting the compiler figure out the type and class?是否可以将指向数据成员的指针作为非类型模板参数传递,同时让编译器找出类型和 class?

You can use a helper to get the type of the class and the member from the type of a member pointer:您可以使用帮助程序从成员指针的类型中获取 class 的类型和成员:

template <typename T> struct type_from_member;

template <typename Cls,typename M>
struct type_from_member<M Cls::*> {
    using class_type = Cls;
    using member_type = M;
};

Then you can use auto and inherit from the helper:然后您可以使用auto并从帮助程序继承:

template <auto member> struct Mem : type_from_member<decltype(member)> {};

using B = Mem<&Struct::x>;

static_assert( std::is_same_v<B::member_type,int>);
static_assert( std::is_same_v<B::class_type,Struct>);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用指向数据成员的指针作为非类型模板参数 - Using a pointer to data member as a non-type template argument 指针作为非类型模板参数 - pointer as non-type template argument 类数据成员指针的非类型模板参数包无法用gcc编译 - Non-type template parameter pack for class data member pointer can't compile with gcc 如何传递模板模板非类型成员函数指针? - How to pass a template template non-type member function pointer? 如何解析成员指针非类型模板参数的组件类型 - how to parse component types of a member pointer non-type template argument 非类型模板参数 - non-type template argument 为什么带有指针子对象的文字 class 类型的 constexpr 表达式不能是非类型模板参数 - why a constexpr expression of literal class type with a pointer subobject can't be a non-type template argument 指向带有继承的重载成员函数的指针的非类型模板参数 - The non-type template parameter of pointer to overloaded member functions with inheritance 非类型模板函数指向const成员函数 - Non-type template function pointer to const member function 在 C++20 中是否允许通过非类型模板参数中的类类型传递函数指针? - Is passing of a function pointer through a class type in non-type template parameter allowed in C++20?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM