【问题标题】:Template << and >> operators specialization模板 << 和 >> 运算符特化
【发布时间】:2011-02-24 05:48:31
【问题描述】:

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

    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

我将如何修复这些错误?

【问题讨论】:

    标签: c++ templates operators specialization


    【解决方案1】:

    您不需要专门化操作符模板:只需编写一个采用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?

    【讨论】:

    • 首先,流操作符应该在类外定义!其次,如果我在您的解决方案中定义我的运算符,我会收到以下链接器错误:LNK2005: "class ... __cdecl operator&lt;&lt;(class... &amp;,class ... const &amp;) ... already defined。知道为什么吗?
    【解决方案2】:

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

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

    其他专业也可以这样做!

    或者最好听从 James 的建议!

    【讨论】:

    • 我知道我忽略了它,但我从没想过我会错过它。
    猜你喜欢
    • 1970-01-01
    • 2011-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多