Template << and >> operators specialization

谁说胖子不能爱 提交于 2019-12-08 05:23:07

问题


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?


回答1:


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?




回答2:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!