【发布时间】:2016-09-09 05:17:39
【问题描述】:
我写了一个测试程序:
#include <iostream>
#include <type_traits>
using namespace std;
template<class T>
void f(T&& t)
{
cout<<is_const<T>()<<endl;
//++t;
}
int main() {
const int i=0;
f(i);
return 0;
}
它输出“0”,表明T 不是常量!这很奇怪。然后我修改了f:
template<class T>
void f(T&& t)
{
cout<<is_const<T>()<<endl;
++t;
}
然后是编译器错误,说我们正在修改只读t。
那么t 是否可以修改?我的程序中是否存在任何错误假设?
【问题讨论】:
-
@101010 用法正确。
is_const有一个合适的转换运算符。 -
@juanchopanza 感谢我不知道的信息。
-
@juanchopanza
cout<<is_const<T>()<<endl;中的什么会强制它布尔值? -
试试
is_const<std::remove_reference<T>>::value -
@xaxxon 好吧,没有
ostream& operator<<(ostream&, is_const<T>),所以没什么可挑选的。
标签: c++ c++11 templates constants