gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 13:00:03 25 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/16435170/

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