setters和getter的模板 [英] Templates for setters and getters

查看:145
本文介绍了setters和getter的模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不熟悉模板,但我不知道,如果可以使用它们的setter和getter方法。例如在这种情况下:

I am not familiar with templates, but I wonder, if it is possible to use them for setter and getter methods. For example in this situation:

double exmlClass::getA(void) const
{
    return a_;
}



void exmlClass::setA(const double& a)
{
    a_ = a;
}



double exmlClass::getB(void) const
{
    return b_;
}

正如你所看到的,方法几乎是一样的,私有变量(a_,b_,c_)。有没有更优雅的方式来写这些功能,或者是在这种情况下像上面这样做是常见的做法吗?如果它的共同使用模板,我将欣赏示例如何使用它们在上面的代码。

As you can see, methods are almost the same, except they refer to another private variables (a_, b_, c_). Is there a more elegant way to write those functions or it is common practice to do like above in such situations? And if its common to use templates, I would appreciate example how you would use them in code above.

另一个问题,我会问是getters和setters应该如何正确声明。是否良好的编码风格?

Another question I would ask is how should getters and setters be properly declared. Is it good coding style?

double getA(void) const;
void setA(const double& a);

double getB(void) const;
void setB(const double& b);

double getC(void) const;
void setC(const double& c);

我的意思是应该getter总是const和setters作为参数引用一个对象, ,这可能会有点慢?

I mean should getters be always const and setters take as argument reference to an object, rather than copy it, which would be probably a little bit slower?

推荐答案

哈罗给那些日本人!

Boost.Fusion。地图是您要查找的基础。

namespace result_of = boost::fusion::result_of;

class MyClass
{
public:
  struct AType {};
  struct BType {};
  struct CType {};

  template <typename Type>
  typename result_of::at< DataType, Type >::type &
  access(Type) { return boost::fusion::at<Type>(mData); }

  template <typename Type>
  typename result_of::at< DataType, Type >::type const &
  get(Type) const { return boost::fusion::at<Type>(mData); }

  template <typename Type>
  void set(Type, typename result_of::at< DataType, Type >::type const & v)
  {
    boost::fusion::at<Type>(mData) = v;
  }

private:
  typedef boost::fusion::map <
    std::pair<AType, int>,
    std::pair<BType, std::string>,
    std::pair<CType, float> > DataType;
  DataType mData;
};

这篇关于setters和getter的模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆