gpt4 book ai didi

c++ - std::add_const 和类似的用例

转载 作者:太空宇宙 更新时间:2023-11-04 12:42:35 29 4
gpt4 key购买 nike

<type_traits> 中的一些类型转换也可以使用核心语言语法来表达(例如 std::add_const<T>::type 是/似乎等同于 const T )。 std::add_lvalue_reference 的 Dtto ,也许还有其他人。这些类型特征有什么用?

我完全理解如果没有它们,标准将提供一个“不完整的工具箱”,我可以想象以元方式使用,如下所示:

template<typename In, template <typename> class Modifier>
struct Apply {
typedef typename Modifier<T>::type Out;
};

Apply<int, std::add_const>

这些特征是否有任何其他可以在句法上表达的用例,或者它们只是“出于完整性感”而被包含在内并用于偶尔的元使用?

最佳答案

这些特性来自 Boost 和将它们添加到标准的提案,N1345 , 引用 Andrei Alexandrescu 的话:

"I understand the symmetry argument for adding add_const, add_volatile, add_cv, and add_pointer, however I would argue in favor of eliminating them. The language-provided equivalents are just simpler and nicer."

同样的提案也给出了这样的理由:

Author's Note: superficially the add_const, add_volatile and add_cv classes are irrelevant, since, for example, add_const::type is the same as T const, for all T (currently this does not apply to function types - but issue 295 addresses this). However the experience from boost is that several users have asked for these templates to be present in the library for the following reasons: (a) Some users find these more explicit - when combining transformation templates in particular, users like the kind of "built in documentation" that these templates provide. (b) Not all users are aware that cv-qualifying a reference is allowed and has no effect, or that cv-qualifying a type that is already cv-qualified is allowed and has no effect. (c) Compilers may emit warnings when cv-qualifying a type that is a reference, or already has a cv-qualifier, these templates can be implemented such that these messages are suppressed in these cases.

此外,对于 add_reference(在标准中重命名为 add_lvalue_reference):

Author's Note: the add_reference template was one of the original motivations behind the boost type traits library. However the resolution to issue 106 makes the template appear largely redundant. In spite of that add_reference may well be useful in suppressing compiler warnings when inadvertently creating references to references in template code.

关于c++ - std::add_const 和类似的用例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53454419/

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