Background
I have some generic code for persistence that uses boost::variant to store multiple types. While outputting values, I had to write a converter function protected_backslash_n, which does nothing, in the default case, but return the same value back.
In the specialised case where the template parameter is a std::string I use boost::regex_replace() to search for \n and replace it with \\n.
Question
The code works fine, but it would be nice if I could get rid of the extra copy in the generic case, due to the return-by-value.
Is there a way to do this while allowing the specialised std::string version to work fine?
I tried changing the return value to T const&, but then the specialised version won’t match up.
Error
GetPipedValues.hpp:15:21: error: template-id ‘protect_backslash_n<std::string>’ for ‘std::string pitbull::protect_backslash_n(const string&)’ does not match any template declaration
Code
template<typename T>
inline T protect_backslash_n( T const& orig )
{
return orig; // BAD: extra copy - how do I get rid of this?
}
template<>
inline std::string protect_backslash_n<std::string>( std::string const& orig )
{
boost::regex expr("(\\n)");
std::string fmt("(\\\\n)");
return boost::regex_replace(
orig, expr, fmt, boost::match_default | boost::format_all
);
}
Don’t make it a template, but just an overload. The compiler will choose that function over a template instantiation, if the parameter matches.