1

我想在一个类中对>>and<<运算符进行模板化,但我也想将它们专门用于字符串,所以我这样做了;

    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;
}

但我得到了一些编译器错误:

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

我将如何解决这些错误?

4

2 回答 2

11

您不需要专门化运算符模板:只需编写一个带 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 */ 
    }
};

函数模板特化很糟糕,应该尽可能避免。有关更多信息,请参阅 Herb Sutter 的Why Not Specialize Function Templates?

于 2011-02-24T05:52:12.930 回答
2

您忘记使用类解析运算符::

template<>
inline sql_command& sql_command::operator>> <std::string> (const std::string& arg)
                      see this ^^ 

为其他专业也这样做!

或者最好听从詹姆斯的建议!

于 2011-02-24T05:51:25.167 回答