Currently, I have a function template like this that converts a vector into a string (just a natural string, separating the elements with a comma):
//the type T must be passable into std::to_string
template<typename T>
std::string vec_to_str(const std::vector<T> &vec);
As you can see, this is only meant for vectors whose elements can be passed into the built-in std::to_string function (such as int, double, etc.)
Is it considered a good practice to document with comments the allowed T? If not, what should I do? Is it possible to enforce this in a better way?
Since
std::to_stringis a C++11 feature, I guess you might be open to a C++11 solution. In this particular case, you can use the trailing return type in a sfinae manner:which would fail to substitute (and eliminate that overload) if the value-type does not work for
to_string. But still, that’s not necessarily the most eye-pleasing way to document and enforce the rule. There is probably a pre-C++11 version of the above Sfinae trick too, but it won’t be any prettier.In general, I would say that it’s fine to simply document it in the comments (possibly with a doxygen tag, like
\tparam). You could use a concept-check mechanism, in the style of Boost.Concept-Check if you want.As a side note, for this specific case, I might recommend that you rely on the
std::ostreamoperator <<instead of theto_stringfunction, since it is more likely that custom types (e.g., a 2D vector or something) will be equipped with an overload for outputting to a stream.