gpt4 book ai didi

c++ - && 在此代码中的优势是什么?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:38:11 25 4
gpt4 key购买 nike

在下面的代码中,使用&&有什么好处?代码来自 Specialize same operator for different traits 处的答案。

来自 this问题,我得到一个 && 参数意味着它是一个可以被函数修改的引用。

decay_t 可能会阻止编译器将对变量的引用解释为数组,如 What is std::decay and when it should be used?

std::forward 是描述的完美转发 here .为什么我们需要这个转发?

谢谢。

#include <iostream>
#include <type_traits>
#include<utility>

class A;

template <typename T>
struct is_A : std::false_type {};
template <> struct is_A<A> : std::true_type {};

template <typename T>
struct is_int : std::false_type {};
template <> struct is_int<int> : std::true_type {};
template <> struct is_int<long> : std::true_type {};

class A{
public:
int val;

void print(void){
std::cout << val << std::endl;
}

template <typename T1>
std::enable_if_t<is_int<std::decay_t<T1>>::value, void>
operator=(T1 && input){
val = 2*std::forward<T1>(input);
}

template <typename T1>
std::enable_if_t<is_A<std::decay_t<T1>>::value,void>
operator=(T1 && Bb){
val = 5*std::forward<T1>(Bb).val;
}
};

int main(void){
A Aa;
A Bb;
int in_a = 3;
Aa = in_a;
Bb = Aa;
Aa.print(); //This should give 6. (3x2)
Bb.print(); //This should give 30. (6x5)
}

最佳答案

实际上,这是一个(让我说)技巧,因此示例代码可以正常工作。
事实上,该标准说:

A user-declared copy assignment operator X::operator= is a non-static non-template member function of class X with exactly one parameter of type X, X&, const X&, volatile X& or const volatileX&.

另外:

If the class definition does not explicitly declare a copy assignment operator, one is declared implicitly. 

现在,尝试复制分配一个常量引用给变量,例如:

Bb = static_cast<const A&>(Aa);

结果将不再是预期的结果。

无论如何,只要您只处理非 cv 限定的左值/右值引用,答案中使用的转发引用就可以正常工作,如示例代码所示。
拦截一堆特定类型并完成它的工作。就这样。

正如@Jarod42 在评论中提到的:

Note that you still have to write the operator=(const A&) to handle it as it is special.

确实没那么特别。如果您不定义它,那么您在该代码中就没有合适的复制赋值运算符。
正如评论中所说,定义它

[...] is left as an exercise to the reader. :-)

那么,这样做有什么好处呢?
提供最小化工作解决方案的捷径。当然,这不是完整的、可用于生产的代码。

关于c++ - && 在此代码中的优势是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39534944/

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