Template setters
{ Reformatted; please limit your lines to 70 characters -mod }
Hi,
Recently I was wondering about trying out a new approach to writing
setters in classes. Traditional pre-C++11 approach relied on passing
const & for complex types and value for simple ones, like int. That
didn't sit well with me, because:
1. It doesn't take advantage of modern C++11 features, like move
semantics.
2. Introduces inconsistency.
So I began to wonder about passing universal references (as per Scott
Meyers' terminology) instead. With this approach all setters would
take the form of:
template<class T>
void setWidget(T &&widget)
{
mWidget = std::forward<T>(widget);
}
This has some pros and cons:
+ Takes into account move semantics.
+ Allows utilization of any form of operator =.
+ Retains consistency across all types (const & vs. value arguments).
- Breaks encapsulation, as the definition needs to be visible.
- Moves possible type mismatch errors inside the setter, instead of
invocation.
- Can lead to confusion, as the setter becomes a type sink (although
the argument can be ruled out, since it propagates to operator =
overloads).
In my opinion the advantages outweigh the disadvantages, although
moving the point of possible error is a strong one. That's why I'm yet
to decide if I should make this my standard practice. Any thoughts?
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]