简体   繁体   English

通用引用和重载

[英]universal references and overloads

Say I have two overloads of a method in a class, set_value which each take a universal reference. 假设我在类set_value有两个方法重载,每个重载都具有一个通用引用。 I'd like to have one function call the other to avoid code duplication, but I'm not sure which is the correct way to give the universal reference to the other function. 我想让一个函数调用另一个函数以避免代码重复,但是我不确定哪一种是对另一函数进行通用引用的正确方法。

template <typename U>
void set_value(U&& value) {
    this->value_ = std::forward<U>(value);
}

template <typename U>
void set_value(U&& value, int overloaded) {
    // which is the correct way to use the other `set_value` overload?
    set_value(value); // just use value directly?
    set_value(std::forward<U>(value)); // or should I forward it?
}

If you want perfect forwarding of value , use std::forward 如果您想完美地传递value ,请使用std::forward

Even though value might be bound to an rvalue, when you use it by name inside set_value it is an lvalue. 即使value 可能绑定到右值,但在set_value按名称使用它时,它也是左值。 Therefore, if you do set_value(value); 因此,如果您执行set_value(value); the universal reference in the one-parameter overload would be bound to an lvalue reference. 单参数重载中的通用引用将绑定到左值引用。

We can confirm this by adding doing something like this: 我们可以通过添加类似以下内容来确认这一点:

template<class T> class TD;  // Allows us to view type deduction results in
                             // the form of compilation errors.
                             // (From "Effective Modern C++")

...

template <typename U>
void set_value(U&& value) {
    TD<decltype(value)> td;
}

...

int i;
set_value(i, 0);
set_value(3, 0);

When forwarding is used, this will give you a compilation error that will reveal the type of value to be int& for set_value(i, 0); 使用转发时,这将给您带来编译错误,该错误将显示set_value(i, 0); int& value类型set_value(i, 0); . If you comment out that statement you'll get a compilation error for set_value(3, 0); 如果注释掉该语句,则会收到set_value(3, 0);的编译错误set_value(3, 0); revealing the type of value to be int&& . 揭示int&&value类型。
If you remove the forwarding you'll get int& in both cases. 如果删除转发,两种情况下都将得到int&

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM