我有一个带有重叠运算符的类。
class sout {
public:
template<typename T>
friend inline sout& operator&(sout&, T&);
friend inline sout& operator&(sout&, std::string&);
};
现在,如果我在 sting.operator& 中使用模板化的 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) 而不是引用。有可能在一行中做到这一点吗?