开发者

Passing in member variables of a specified class

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜