Do `const T` and `T` have no difference when taking its nested type?

。_饼干妹妹 提交于 2021-02-07 18:44:00

问题


#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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!