I want to create a template function that generates a string representation of an array of things that have a name()
method. The things might be kept by value, or by reference (raw or smart)
template< typename T>
struct GetStringRepresentation;
template< typename T>
struct GetStringRepresentation< std::vector< std::unique_ptr< T > > >
{
inline void ()( const std::vector< std::unique_ptr< T > >& seq, std::string& out )
{
size_t size = seq.size();
for (int i=0; i< size; i++)
{
if (i > 0)
out += ", ";
out += seq[i]->name();
}
}
};
template< typename T>
struct GetStringRepresentation< std::vector< std::shared_ptr< T > > >
{
inline void ()( const std::vector< std::shared_ptr< T > >& seq, std::string& out )
{
size_t size = seq.size();
for (int i=0; i< size; i++)
{
if (i > 0)
out += ", ";
out += seq[i]->name();
}
}
};
template< typename T>
struct GetStringRepresentation< std::vector< T* > >
{
inline void ()( const std::vector< T* >& seq, std::string& out )
{
size_t size = seq.size();
for (int i=0; i< size; i++)
{
if (i > 0)
out += ", ";
out += seq[i]->name();
}
}
};
template< typename T>
struct GetStringRepresentation< std::vector< T > >
{
inline void ()( const std::vector< T >& seq, std::string& out )
{
size_t size = seq.size();
for (int i=0; i< size; i++)
{
if (i > 0)
out += ", ";
out += seq[i].name();
}
}
};
As you can clearly see, there is a bunch of duplication, specially between the reference specializations. I'm not very up to speed with the best way to do this, i would like to see a better way that removes some, or all of the code duplication