I want to template the >>
and <<
operators in a class, but I would also like to specialize them for strings, so I did this;
class sql_command
{
public:
sql_command() { }
explicit sql_command(std::string& cmd)
: m_raw(cmd) {
}
inline sql_command& operator<<(const char * arg)
{
m_raw += arg;
return *this;
}
inline sql_command& operator<<(const std::string& arg)
{
m_raw += arg;
return *this;
}
template<typename T>
inline sql_command& operator>>(const T arg)
{
m_raw += boost::lexical_cast<std::string>(arg);
return *this;
}
inline std::string const& command() const {
return m_raw;
}
private:
std::string m_raw;
};
template<>
inline sql_command& operator>> <std::string> (const std::string& arg) {
m_raw += "'";
m_raw += arg;
m_raw += "'";
return *this;
}
template<>
inline sql_command& operator>> <char*>(const char * arg) {
m_raw += "'";
m_raw += arg;
m_raw += "'";
return *this;
}
But I got some compiler errors:
1>.\main.cpp(83) : error C2912: explicit specialization; 'sql_command &operator >><std::string>(const std::string &)' is not a specialization of a function template
1>.\main.cpp(83) : error C2805: binary 'operator >>' has too few parameters
How would I fix these errors?
You don't need to specialize the operator template: just write an overload taking a std::string
:
class sql_command {
/* ... */
template<typename T>
sql_command& operator>>(const T& arg) {
/* general purpose implementation */
}
sql_command& operator>>(const std::string& arg) {
/* special std::string implementation */
}
};
Function template specialization is yucky and should be avoided wherever possible. For more information, consult Herb Sutter's Why Not Specialize Function Templates?
You forgot to use class resolution operator ::
template<>
inline sql_command& sql_command::operator>> <std::string> (const std::string& arg)
see this ^^
Do this for other specialization also!
Or better follow James advice!
来源:https://stackoverflow.com/questions/5100866/template-and-operators-specialization