gpt4 book ai didi

c++ - 将 std::decay 与 std::forward 一起使用

转载 作者:行者123 更新时间:2023-12-03 06:53:36 27 4
gpt4 key购买 nike

template<typename T>
struct test
{
std::string key;
T value;

template<typename U>
using decay = typename std::decay<U>::type;

template<typename U = decay<T>, typename US = decay<std::string>>
test(U&& _value, US&& _key) : value(std::forward<U>(_value)), key(std::forward<US>(_key)){}
};

我几乎在每个项目中都使用这样的衰减。我想问一下,写这样的东西是否有用:

test(T&& _value, std::string&& _key) : value(std::move(_value)), key(std::move(_key)){}
test(const T& _value, std::string&& _key) : value(_value), key(std::move(_key)){}
test(T&& _value, const std::string& _key) : value(std::move(_value)), key(_key){}
test(const T& _value, const std::string& _key) : value(_value), key(_key){}

最佳答案

你想多了。你只需要这个:

template<typename T>
struct test
{
std::string key;
T value; // as a safety this could be replaced by:
// typename std::decay<T>::type value;

template<typename U, typename US>
test(U&& _value, US&& _key)
: value(std::forward<U>(_value))
, key(std::forward<US>(_key))
{}
};

这种完美的转发将确保您列出的所有构造函数都可用。

看来你没明白什么std::decay做,或何时/如何使用它。示例:decay<std::string>毫无意义,因为这只代表 std::string类型,所以你应该只写 std::string您不必进行任何转换,因为您可以完全控制传递给 decay 的类型,您知道此类型不包含引用或常量,因为您已明确键入此内容。

std::decay对于定义您可以分配给的类型的变量/字段很有用。它剥离引用和​​常量,C 数组转换为指针,并确保指针指向函数。参见 doc示例。

您能否解释一下您计划使用模板参数的默认类型实现什么?我不明白你在这里的意图是什么。

关于c++ - 将 std::decay 与 std::forward 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64374589/

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