Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Templates for setters and getters

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_;
}

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.

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);

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?

like image 510
Overpain Avatar asked Nov 16 '10 14:11

Overpain


2 Answers

Haro to the naysayers!

Boost.Fusion.Map is what you're looking for as a basis.

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;
};
like image 53
Matthieu M. Avatar answered Sep 27 '22 19:09

Matthieu M.


design your programs in a way, that there is less need for getters and setters. You could create them by a macro or implement some kind of propertysyntax(which is possible but there are always things that don't work right).. However, I suppose just writing the accessors when they are needed or generate them with your IDE is the best and most usual way.

As for your second question, you should use it at least for object type, you don't really need it for primitives. Personally I don't use it either if I need a copy of the object anyway, however others may claim that it might be better to do this explicit.

like image 21
DaVinci Avatar answered Sep 27 '22 19:09

DaVinci