[英]Perfect forwarding for returned value?
我正在重载operator[]
:
const Type&& operator[](int index) const {
if (index >= size) { std::cout << "Error: excessive index.\n"; return 0; }
else if (index < 0) { std::cout << "Error: negative index.\n"; return 0; }
else {
Node* temp = head->next;
for (int i = 0; i < index; i++) { temp = temp->next; }
return temp->value;
}
}
但我需要它的副本,它将返回非常量类型值。 我读到,当 function 的 arguments 既可以是 const 也可以是非 const 的情况下,我们可以使用完美转发(这样我们每次使用它时都将它们包装在forward<Type>
中),但是如何将它用于返回的值?
另外,如果我只是想什么都不返回,我应该写return 0;
或return NULL;
? 哪个更容易理解?
目前不支持这种适用于所有参数的统一语法, const
/ volatile
/non- const
/lvalue/rvalue/etc.,隐式 object 参数。 但是,有提案P0847r4: Deducing this增加了这个功能。 有了这个,你可以说:
template <typename Self>
auto&& operator[](this Self&& self, int index)
{
if (index >= self.size) { throw std::out_of_range("Error: excessive index"); }
else if (index < 0) { throw std::out_of_range("Error: negative index"); }
auto* temp = self.head;
for (int i = 0; i < index; i++) { temp = temp->next; }
return std::forward_like<Self>(temp->value);
}
Until it becomes available, the best what you can do is to shorten the implementation for const
and non- const
overloads, and delegate both calls to a static helper function template, that actually can deduce the cv-qualification and value category of the implicit object范围:
class List
{
private:
template <typename Self>
static auto&& get(Self&& self, int index)
{
if (index >= self.size) { throw std::out_of_range("Error: excessive index"); }
else if (index < 0) { throw std::out_of_range("Error: negative index"); }
Node* temp = self.head;
for (int i = 0; i < index; i++) { temp = temp->next; }
return temp->value;
}
public:
const Type& operator[](int index) const
{
return get(*this, index);
}
Type& operator[](int index)
{
return get(*this, index);
}
private:
// ...
};
另外,请注意 function 返回引用的惯用方法是在无法返回任何内容的情况下抛出异常,或者插入临时并返回新的 object。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.