【发布时间】:2018-03-29 04:32:39
【问题描述】:
作为了解std::enable_if 用法的练习,我尝试实现一个包装类(结构)来表示任何给定时间点的特定类型:
#include<type_traits>
#include<typeinfo>
#include<iostream>
using std::enable_if;
using std::is_same;
using std::cout;
using std::endl;
template<typename T>
struct type_wrap{
type_wrap(typename enable_if<is_same<int,T>::value,T>::type&& rrT):value(rrT){
cout << "The wrapped type is " << typeid(value).name() << endl;
cout << "The wrapped value is " << value << endl;
}
type_wrap(typename enable_if<is_same<float,T>::value,T>::type && rrT):value(rrT){
cout << "The wrapped type is " << typeid(value).name() << endl;
cout << "The wrapped value is " << value << endl;
}
T& value;
};
int main(){
type_wrap<int>(0);
type_wrap<float>(0.5);
return(0);
}
以上代码无法编译:
so_main.cpp:16:47: error: no type named 'type' in 'std::__1::enable_if<false, int>'; 'enable_if' cannot be used to disable this declaration
type_wrap(typename enable_if<is_same<float,T>::value,T>::type && rrT):value(rrT){
^~~~~~~~~~~~~~~~~~~~~~~
so_main.cpp:26:9: note: in instantiation of template class 'type_wrap<int>' requested here
type_wrap<int>(0);
^
so_main.cpp:12:47: error: no type named 'type' in 'std::__1::enable_if<false, float>'; 'enable_if' cannot be used to disable this declaration
type_wrap(typename enable_if<is_same<int,T>::value,T>::type&& rrT):value(rrT){
^~~~~~~~~~~~~~~~~~~~~
so_main.cpp:27:9: note: in instantiation of template class 'type_wrap<float>' requested here
type_wrap<float>(0.5);
^
2 errors generated.
如果我要删除其中一个重载的构造函数以及来自main() 的相应实例化,则该代码有效。但这违背了本练习的全部目的。
有人能指出编译错误的原因吗?
【问题讨论】: