模板<<和>>运营商专业化 [英] Template << and >> operators specialization

查看:90
本文介绍了模板<<和>>运营商专业化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在一个类中为>><<运算符建立模板,但是我也想将它们专门用于字符串,所以我做到了;

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?

推荐答案

您不需要专门设置运算符模板:只需编写一个带有std::string的重载即可:

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

功能模板的专业化令人讨厌,应尽可能避免.有关更多信息,请查阅Herb Sutter的为什么不专门设置功能模板?

Function template specialization is yucky and should be avoided wherever possible. For more information, consult Herb Sutter's Why Not Specialize Function Templates?

这篇关于模板&lt;&lt;和&gt;&gt;运营商专业化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆