显式调用模板化重载运算符

use*_*087 2 c++ templates casting operator-overloading

我有一个带有重叠运算符的类.

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

  friend inline sout& operator&(sout&, std::string&);
};
Run Code Online (Sandbox Code Playgroud)

现在,如果我使用模板化运算符和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;
}
Run Code Online (Sandbox Code Playgroud)

错误:

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)'
Run Code Online (Sandbox Code Playgroud)

比我试图使用explicite运算符&template-type by:

operator&<uint16_t>(s, ts);  // this also ig ok
Run Code Online (Sandbox Code Playgroud)

但如果我把它合并,我又一次错误:

operator&<uint16_t>(s, static_cast<uint16_t>(str.size())
Run Code Online (Sandbox Code Playgroud)

错误:

'operator &' : cannot convert parameter 2 from 'uint16_t' to 'uint16_t &'
Run Code Online (Sandbox Code Playgroud)

我也试过reinterpret_cast.

我知道operator&期望对uint16_t的引用,而size()函数返回的是size_t(int)而不是引用.是否有可能在一行中做到这一点?

And*_*owl 7

问题是返回的值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()
}
Run Code Online (Sandbox Code Playgroud)

左值引用不能绑定到右值,除非它们是引用const.

template<typename T>
friend inline sout& operator&(sout&, T const&);
//                                     ^^^^^
Run Code Online (Sandbox Code Playgroud)

如果你operator&应该修改右手参数,以便引用不能引用const,在C++ 11中你可以使用rvalue引用(由于C++ 11的引用折叠规则,这也允许绑定到左值) ):

template<typename T>
friend inline sout& operator&(sout&, T&&);
//                                   ^^^
Run Code Online (Sandbox Code Playgroud)