开发者

Passing in member variables of a specified class

开发者 https://www.devze.com 2022-12-19 13:26 出处:网络
I want to pass in the name of a member variable. I thought I could do this by template <typename T::*>

I want to pass in the name of a member variable. I thought I could do this by

template <typename T::*>
voi开发者_如何学God SetVal(T::* newval)
{

};

This obviously doesn't work, but hopefully gets across what I'm trying to do. I want to be able to set a certain member variable of the templated class.


You can always put compilation-defined constant as template arguments. So here that would be:

template <typename T, typename R, R T::* member>
R& SetVal(T& t, const R& value)
{
   t.*member = value;
   return t.*member;
}

struct A
{
  int a;
};

int main()
{
  A a;
  SetVal<A,int,&A::a>(a, 10);
  return 0;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号