c++ - how to parse component types of a member pointer non-type template argument -


in example code below class b has 3 template arguments. wonder if first 2 arguments can inferred third one, on opinion contains necessary information. right using macro, avoid tediously repeating same names multiple times in various combination. think there should better way.

in main show ideally write.

the goals class b are: 1) variable member pointer should explicitly non-type template argument of class 2) should work different classes (e.g. a1, a2) , member variables of different types. how can class b rewritten achieve goals above , allow defined 1 template argument?

#include <iostream>  struct a1 {     int m_n;     a1() : m_n(10) {} };  struct a2 {     double m_x;     a2() : m_x(2.1) {} };  #define xxx(cls, member) cls, decltype(cls::member), &cls::member  // b have last template argument template <typename c, typename t, t c::*p> struct b {     b(c& cls) : m_c(cls), m_v(cls.*p) {};     void set(t v) { m_v = v; }     void save() { m_c.*p = m_v; }     c& m_c;     t m_v; };  int main() {     a1 a1; std::cout << "a1.n=" << a1.m_n << std::endl;     a2 a2; std::cout << "a2.x=" << a2.m_x << std::endl;      // write     typedef b<xxx(a1,m_n)> m1_n_t;     typedef b<xxx(a2,m_x)> m2_x_t;     // woukd write     //typedef b<&a1::m_n> m1_n_t;     //typedef b<&a2::m_x> m2_x_t;      // how use     m1_n_t b1(a1); b1.set(5); b1.save(); std::cout << "a1.n=" << a1.m_n << std::endl;     m2_x_t b2(a2); b2.set(3.4); b2.save(); std::cout << "a2.x=" << a2.m_x << std::endl;      return 0; } 

you have this:

template <class type> struct member_object;  template<typename rettype, typename classtype>  struct member_object<rettype classtype::*> {     using return_type = rettype;     using class_type = classtype;     using member_type = rettype classtype::*; }; 

live demo

notice in a, n private, fail compile in decltype(&a::n) unless make public.


if need actual pointer @ compile time have pass in explicitly template argument this:

template <class ptrtype, ptrtype ptr> struct member_object;  template<typename rettype, typename classtype, rettype classtype::* ptr>  struct member_object<rettype classtype::*, ptr> {     using return_type = rettype;     using class_type = classtype;     using member_type = rettype classtype::*; }; 

Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -