簡體   English   中英

顯式調用模板化重載運算符

[英]explicit call of templated overloaded operator

我有一個帶有重疊運算符的類。

class sout {
public:
  template<typename T>
  friend inline sout& operator&(sout&, T&);

  friend inline sout& operator&(sout&, std::string&);
};

現在,如果我使用模板化運算符和sting.operator內部,我得到一個錯誤:

碼:

sout& operator&(sout& s, std::string& str) {
  uint16_t ts = static_cast<uint16_t>(str.size());  // this is ok
  s & ts; // is also ok

  s & static_cast<uint16_t>(str.size());  // but this is wrong

  // ...
  return s;
}

錯誤:

Error:C2679: binary '&' : no operator found which takes a right-hand operand of type 'uint16_t' (or there is no acceptable conversion)
could be 'sout &operator &<uint16_t>(sout &,T &)'
with
[
    T=uint16_t
]
or       'sout &operator &(sout &,std::string &)'
while trying to match the argument list '(sout, uint16_t)'

比我嘗試通過以下方式使用顯式運算符&模板類型:

operator&<uint16_t>(s, ts);  // this also ig ok

但如果我把它合並,我又一次錯誤:

operator&<uint16_t>(s, static_cast<uint16_t>(str.size())

錯誤:

'operator &' : cannot convert parameter 2 from 'uint16_t' to 'uint16_t &'

我也試過reinterpret_cast。

我知道operator&期望對uint16_t的引用,並且size()函數返回的是size_t(int)而不是引用。 是否有可能在一行中做到這一點?

問題是size()返回的值是臨時值,臨時值是rvalues; 但是,您的函數接受左值引用。 以下代碼段闡明了問題:

int foo() { return 42; }
void bar(int& i) { i++; } // Parameter is an lvalue reference to non-const

int main()
{
    bar(foo()); // ERROR! Passing an rvalue to bar()
    bar(1729); // ERROR! Passing an rvalue to bar()

    int i = 42;
    bar(i); // OK! Passing an lvalue to bar()
}

左值引用不能綁定到右值,除非它們是對const引用。

template<typename T>
friend inline sout& operator&(sout&, T const&);
//                                     ^^^^^

如果您的operator&應該修改右手參數,以使該引用不能是const的引用,則在C ++ 11中,您可以使用rvalue引用(由於C ++ 11的引用,這也可以綁定到lvalues崩潰規則):

template<typename T>
friend inline sout& operator&(sout&, T&&);
//                                   ^^^

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM