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
,您知道此类型不包含引用或const,因为您具有此类型明确地。
std::decay
在定义可以分配给它的类型的变量/文件时很有用。它去除引用和常量性,C数组转换为指针,并确保指向函数的指针。请参阅文档示例。
您能否解释一下使用模板参数的默认类型要实现的计划?我不知道你在这里打算什么。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句