I\'d like to write a function template that operates on a container of strings, for example a std::vector.
I\'d like to support both CString
One common way to solve this is to extract the required interface out into a trait class. Something like this:
template
struct StringTraits
{
static size_t size(const S &s) { return s.size(); }
// More functions here
};
template
void DoSomething(const ContainerOfStrings& strings)
{
for (const auto & s : strings)
{
auto len = StringTraits::type>::size(s);
}
}
// Anyone can add their own specialisation of the traits, such as:
template <>
struct StringTraits
{
static size_t size(const CString &s) { return s.GetLength(); }
// More functions here
};
Of course, you can then go fancy and change the function itself to allow trait selection in addition to the type-based selection:
template >
void DoSomething(const ContainerOfStrings& strings)