我学习了类型特征和类型转换(修改?),所以我遇到了std::remove_reference
。我试图像这样实现它:
template <class T>
struct remove_reference { typedef T type; };
template <class T>
struct remove_reference<const T> { typedef const T type; };
template <class T>
struct remove_reference<T&> { typedef T type; };
template <class T>
struct remove_reference<const T&> { typedef const T type; };
现在我使用它时:
remove_reference<int>::type x1; // x1 is int : Ok
remove_reference<const int>::type x2; // x2 is <type> : ???
remove_reference<int&>::type x3; // x3 is int : Ok
remove_reference<const int&>::type x4; // x4 is <type> : ???
我使用的是Visual Studio 2015,它告诉我x2
和x4
的类型是<type>
所以我在这里缺少什么?
注意:
{ typedef const T type }
删除引用并保持常量... 编辑:std :: remove_reference没有任何问题,我只是为了学习而这样做...
答案 0 :(得分:2)
我正在
{ typedef const T type }
删除引用并保持常量...
你不需要这样做。如果您从T&
T
const X
移除const X
,那么您将获得template <class T>
struct remove_reference { typedef T type; };
template <class T>
struct remove_reference<T&> { typedef T type; };
template <class T>
struct remove_reference<T&&> { typedef T type; };
。没有必要专门为此。
你做需要处理rvalue引用。
所以你的实现应该是:
const
但这并没有改变你的测试无效的事实。使用最新版本的VC ++,我得到了更多有用的错误:
main.cpp(16):错误C2734:&#39; x2&#39;:&#39; const&#39;如果不是“外部”,则必须初始化对象 main.cpp(18):错误C2734:&#39; x4&#39;:&#39; const&#39;如果不是&#39; extern&#39;
,则必须初始化对象这正确地告诉您,您正在尝试定义remove_reference
而不给它赋值。这是不允许的,因为它会有一个不确定的(即垃圾)值,你无法设置它!
这与您的int x1;
const int x2; // error!
int x3;
const int x4; // error!
无关,如果你写了这个错误,你会得到同样的错误:
remove_reference<int>::type x1; // x1 is uninitialized
remove_reference<const int>::type x2 = 0;
remove_reference<int&>::type x3; // x3 is uninitialized
remove_reference<const int&>::type x4 = 0;
如果初始化const变量,您的测试将正常工作:
public void run() {
// TODO Auto-generated method stub
super.run();
if(getName().equals("InputScanner")){
synchronized (this) {
while(true){
System.out.print("\nInput Scanner ");
try {
{
/*String str=*/s1.next();
System.out.print("yes");
} Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}}
else{
System.out.print("Thread Id"+getId());
MonitorDirectory md=new MonitorDirectory();
md.monitor(path);
}
}