I've tried following codes in cppinsights:
#include <iostream>
#include <string>
#include <type_traits>
#include <vector>
template<typename T>
void printType(T x) {
std::cout << typeid(x).name() << std::endl;
}
void test() {
const std::vector<int>::pointer a = new int[2];
const int* c = new int[2];
printType(a);//line15
printType(c);//line16
//delete
}
int main() {
test();
}
The output is like:
/* First instantiated from: insights.cpp:15 */
#ifdef INSIGHTS_USE_TEMPLATE
template<>
void printType<int *>(int * x)
{
std::operator<<(std::cout, typeid(x).name()).operator<<(std::endl);
}
#endif
/* First instantiated from: insights.cpp:16 */
#ifdef INSIGHTS_USE_TEMPLATE
template<>
void printType<const int *>(const int * x)
{
std::operator<<(std::cout, typeid(x).name()).operator<<(std::endl);
}
#endif
Since std::vector<int>::pointer
= int*
, why const std::vector<int>::pointer a
has been interpreted as int*
instead of const int*
?
BTW: If the pointer
is replaced by value_type
, they will be both deduced as int
instead of const int
.
How compiler deal with const
in this type of cases?
CodePudding user response:
Since
std::vector<int>::pointer = int*
, whyconst std::vector<int>::pointer
a has been interpreted asint*
instead ofconst int*
?
Because const std::vector<int>::pointer
will be interpreted as int* const
instead of const int*
. Adding a const
-qualifier to a pointer makes itself unmodifiable, not the value it points to.
If you need const int*
then you should use std::vector<int>::const_pointer
instead of const std::vector<int>::pointer
.
CodePudding user response:
why const
std::vector<int>::pointer a
has been interpreted as int* instead of const int*?
Because std::vector<int>::pointer
is int*
. A const qualified int*
is int* const
. It is not const int*
aka int const *
which is a distinct type. But the constness of the argument has no effect on deduction of the template, so it won't be deduced as int* const
.