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

时间:2013-04-25 15:52:47

标签: c++ templates casting operator-overloading

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

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

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

现在,如果我使用模板化运算符&amp;在sting.operator&amp;我收到一个错误:

代码:

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)'

比我试图使用explicite运算符&amp;模板类型:

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。

我知道运营商&amp;期待对uint16_t的引用,而size()函数返回的是size_t(int)而不是引用。是否有可能在一行中做到这一点?

1 个答案:

答案 0 :(得分: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()
}

左值引用无法绑定到右值,除非它们是对const的引用。

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

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

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