【发布时间】:2017-09-27 19:15:47
【问题描述】:
案例 1 std::remove_const 的可能实现是
template< class T > struct remove_const { typedef T type; };
template< class T > struct remove_const<const T> { typedef T type; };
当我使用它们时
std::remove_const<int> // use the first version
std::remove_const<const int> // use the second version
案例 2 如果我评论第二个版本
template< class T > struct remove_const { typedef T type; };
//template< class T > struct remove_const<const T> { typedef T type; };
并使用它们
std::remove_const<int> // use the first version
std::remove_const<const int> // use the first version
在案例 1 中,编译器如何决定为 const int 选择第二个版本?
【问题讨论】:
-
我想你是在问部分模板专业化是如何工作的。这很复杂,但这个 wiki 是一个不错的概述:en.cppreference.com/w/cpp/language/partial_specialization。简短的回答是
const int与const T的匹配度比 plain-old-T更接近,所以它是首选。 -
@TravisGockel 感谢您的链接。我已阅读有关模板专业化的信息。但是我看到的示例,对完全不同的类型(例如 int、float、short)使用专门化,但不使用密切相关的类型(例如 int 和 const int)。感谢您的信息
-
当然是有标准的。确切地说,是一个 ISO 标准。虽然官方出版物是专有的,但出版前的最后草稿是向公众提供的(并且几乎与完成的文件相同)。
-
在相关说明中,您不应该在代码中真正使用
remove_const。 100 次中有 99 次,如果你是,那么你可能做错了什么。
标签: c++ std typetraits