【问题标题】:how to code "hello" == obj without overload the operator==? [closed]如何在不重载运算符==的情况下编写“hello”== obj? [关闭]
【发布时间】:2019-08-31 04:49:43
【问题描述】:

我创建了一个类字符串,它是同时使用char*wchar_t 的模板。 我想编译obj == " word" 和相反的情况,而不会为每种情况重载operator==

我已经尝试过使用运算符转换,但它不起作用。

template<typename T>
class String
{
    friend bool operator==<T>(const String<T>& a, const String<T>& b);

public:
    typedef T Type_value;
    String(const Type_value* str = "");
    String(const String& str);
    String& operator=(const String& original);
    operator T* ();
    operator std::string ();

    ~String();

private:
    size_t m_size; 
    Buffer<Type_value> m_buff;
};

template <typename T>
bool operator== (const String<T>& a, const String<T>& b )
{
    return UtilString<T>::Compare(a.m_buff, b.m_buff) == 0;
}


template<typename T>
String<T>::operator T* ()
{
    return reinterpret_cast<T*>(m_buff.Begin());
}

template<typename T>
String<T>::operator std::string ()
{
    return string(m_buff.Begin());
}

我希望"hello" == String&lt;char&gt;("hello") 有效。

【问题讨论】:

  • "word" == "word" 具有未指定的结果,添加 operator == 比添加转换运算符更好/更安全。
  • "没有为每种情况重载 operator==" - 为什么?
  • @WhozCraig:由于 OP 有 bool operator== (const String&lt;T&gt;&amp; a, const String&lt;T&gt;&amp; b ),我认为他希望避免实现 String&lt;T&gt;/const char*/const wchar_t* 之间的所有变体并重用 OP 写的那个。

标签: c++ string templates operator-overloading


【解决方案1】:

问题:

template <typename T>
bool operator== (const String<T>& a, const String<T>& b )

T的减法,对于"hello" == String&lt;char&gt;("hello")"hello"const String&lt;T&gt;&amp;不匹配,所以超载被丢弃。

你可以做的就是让它成为非模板:

template <typename T>
class String
{
    // non template function.
    friend bool operator==(const String& lhs, const String& rhs)
    {
        return UtilString<T>::Compare(a.m_buff, b.m_buff) == 0;
    }
    // ...    

};

所以"hello" == String&lt;char&gt;("hello") 会考虑过载(感谢 rhs)

operator==(const String<char>& lhs, const String<char>& rhs)

并且会从"hello" 构造String&lt;char&gt;,因为构造函数是可行的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-09
    • 2012-08-19
    • 1970-01-01
    • 1970-01-01
    • 2015-01-28
    • 1970-01-01
    相关资源
    最近更新 更多