Which approach is the better one and why?
template<typename T>
struct assistant {
T sum(const T& x, const T& y) const { ... }
};
template<typename T>
T operator+ (const T& x, const T& y) {
assistant<T> t;
return t.sum(x, y);
}
Or
template<typename T>
struct assistant {
static T sum(const T& x, const T& y) { ... }
};
template<typename T>
T operator+ (const T& x, const T& y) {
return assistant<T>::sum(x, y);
}
To explain the things a bit more: assistant has no state it only provides several utility functions and later I can define template specialization of it to achieve a different behavior for certain types T.
I think for higher optimization levels these two approaches don’t lead to different byte codes because anyway the assistant will optimized “away”…
Thanks!
It is usually not a question of run-time performance, but one of readability. The former version communicates to a potential maintainer that some form of object initialization is performed. The latter makes the intent much clearer and should be (in my opinion) preferred.
By the way, what you’ve created is basically a traits class. Take a look at how traits are done in the standard library (they use static member functions).