Pointer to class member as a template parameter

谁说胖子不能爱 提交于 2019-11-28 08:14:22

This could be a solution in C++11:

You can define the following generic type traits:

template<class T>
struct remove_member_pointer {
  typedef T type;
};

template<class Parent, class T> 
struct remove_member_pointer<T Parent::*> {
  typedef T type;
};

template<class T>
struct baseof_member_pointer {
  typedef T type;
};

template<class Parent, class T>
struct baseof_member_pointer<T Parent::*> {
  typedef Parent type;
};

Now you can define an additional, 4-line wrapper macro for every struct:

template<class Class, class Result, Result Class::*Member>
struct _MyStruct {
  // ...
};

#define MyStruct(MemberPtr) \
  _MyStruct<baseof_member_pointer<decltype(MemberPtr)>::type, \
            remove_member_pointer<decltype(MemberPtr)>::type, \
            MemberPtr>

... and use it in the following way:

MyStruct(&SomeClass::value)  myStruct; // <-- object of type MyStruct<&SomeClass:value>

I use this as an intermediate solution, until we switch to C++17.

An answer to my question was proposed in this paper for the next upcoming C++ standard:

This syntax was proposed:

template<using typename T, T t>
struct some_struct { /* ... */ };

some_struct<&A::f> x;

The need for a new syntactical construct indicates that you cannot do that by now.

I hope n3601 will be accepted. :-)

In c++17, with the addition of auto in template arguments (P0127), I think you can now do:

template<auto value>
struct MyStruct {};

template<typename Class, typename Result, Result Class::* value>
struct MyStruct<value> {
    // add members using Class, Result, and value here
    using containing_type = Class;
};

typename MyStruct<&Something::theotherthing>::containing_type x = Something();

Make your result class a child of your template class. assuming the pointer member is an object of your result class in public or whatever, you can access any objects by doing something like this

template <stuff for this class> :: public result
{
    blah
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!