I'm studying c++ template, and write a example as shown below:
#include <vector>
#include <iostream>
#include <type_traits>
#include <typeinfo>
using namespace std;
template <typename T>
void fcn(T &&val)
{
cout << is_same<T, int&>::value << endl;
const T t = val;
//T const t = val;
cout << typeid(t).name() << endl;
t = 10;
cout << "val: " << val;
cout << ", t: " << t << endl;
return;
}
int main()
{
cout << boolalpha;
int i{};
fcn(i);
}
I expect this code can't compile successfully, but there are no error, the output:
true
i
val: 10, t: 10
I have two questions:
gcc deduce the T is
int& type, the lineconst T t = val, means t const bind to val, like this:const int &t = val, why the const has no effect? t and i value can be changed?I used
typeid(t).name()to show the t's type, why just printi?