问题
#include <string>
template<typename T, typename C, typename CR>
void f()
{
typename T::size_type* p1{}; // ok
typename CR::size_type* p2{}; // error
typename C::size_type* p3{}; // Does the C++ standard allow this?
}
int main()
{
f<std::string, const std::string, const std::string&>();
}
Do const T
and T
have no difference when taking its nested type?
回答1:
Indeed, the "nested types" are the same.
A type qualified with const
and/or volatile
is a "version" of the unqualified type ([basic.type.qualifier] in the standard, 6.3.8, paragraph 1) - even if it's not quite the same. This is unlike a pointer or a reference, which, when introduced, form a wholly different type than the type they point or refer to (clauses [dcl.ref] and [dcl.ptr] of the standard, 9.3.3.1 and 9.3.3.2, paragraph 1 in both).
It is also worth mentioning that class-scope types do not get const
-qualified because you get them from the const
version of the type - e.g. std::vector<int>::iterator
is the exact same type as std::add_const_t<std::vector<int>>::iterator
- but not the same type as std::vector<int>::const_iterator
.
来源:https://stackoverflow.com/questions/61430178/do-const-t-and-t-have-no-difference-when-taking-its-nested-type