为什么不能在模板函数中向局部变量添加低级常量类型 我正在学习C++模板,并写一个例子,如下所示: #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); }
我有两个问题:为什么不能在模板函数中向局部变量添加低级常量类型 我正在学习C++模板,并写一个例子,如下所示: #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); },c++,c++11,templates,C++,C++11,Templates,我有两个问题: gcc推断T是int&type,行const T=val,表示T const绑定到val,如下所示:const int&T=val,为什么const没有效果?t和i值可以更改吗 我使用typeid(t).name()来显示t的类型,为什么只打印I 在您的情况下,const TwithT=int&意味着,给出一个我无法重新分配的引用。但是引用永远不可赋值,它总是指向同一个对象。因此它折叠为T,在这种情况下是int& 要使其按预期工作,请使用std::remove\u referen
int&type
,行const T=val
,表示T const绑定到val,如下所示:const int&T=val
,为什么const没有效果?t和i值可以更改吗typeid(t).name()
来显示t的类型,为什么只打印I
const T
withT=int&
意味着,给出一个我无法重新分配的引用。但是引用永远不可赋值,它总是指向同一个对象。因此它折叠为T
,在这种情况下是int&
李>
要使其按预期工作,请使用std::remove\u reference
见:
name
返回实现定义的内容,因此没有什么好说的李>
T
是int&
类型,const T=val
,意味着T const绑定到val,为什么const
没有效果template <typename T> void fcn(T &&val);
我编写了另一个程序来研究
const T
,它使用“type alias”:
#包括
使用名称空间std;
int main()
{
int i{};
使用T=int*;
常数T=&i;//与T常数T=&i;相同;
*t=10;
cout 1.我认为const修改的是右边的,而左边的。2.比你的建议好多了,PRETTY_函数看起来更好。
template <typename T> void fcn(T &&val);
template <class T> p(T&&) { std::cout << __PRETTY_FUNCTION__; }
p(t); // prints out understandable type info
#include <iostream>
using namespace std;
int main()
{
int i {};
using T = int *;
const T t = &i; // same with T const t = &i;
*t = 10;
cout << i << endl;
int j{};
//t = &j; // error, t is int * const
}