gpt4 book ai didi

c++ - 模板化重载运算符的显式调用

转载 作者:搜寻专家 更新时间:2023-10-30 23:59:31 24 4
gpt4 key购买 nike

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

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) 而不是引用。有可能在一行中做到这一点吗?

最佳答案

问题是 size() 返回的值是一个临时值,临时值是右值;但是,您的函数接受一个左值 引用。以下片段阐明了问题:

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()
}

左值引用不能绑定(bind)到右值,除非它们是对 const 的引用。

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

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

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

关于c++ - 模板化重载运算符的显式调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16219367/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com