std::true_type和std::false_type
实际上是类型别名
是两个类型(类模板)
注意区分true_type与false_type与true和false区别
-
true_type
,false_type
代表类型
-
true
,false
代表值
nmsp1::FalseType myfunc1();//返回假这种含义
nmsp1::TrueType myfunc2();//返回真这种含义
自己模拟实现
namespace nmsp1 {
template<bool val>
struct BoolConstant {
using type = BoolConstant<val>;
static constexpr bool value = val;
};
using TrueType = BoolConstant<true>;
using FalseType = BoolConstant<false>;
template<typename T,bool val>
struct AClass
{
AClass() {
cout << "AClass()执行了" << endl;
//if(val) {
// T tmpa = 15;
//}
//else {
// T tmpa = "abc"; //int tmpa = "abc";
//}
//if constexpr (val) {
// T tmpa = 15;
//}
//else {
// T tmpa = "abc"; //int tmpa = "abc";
//}
AClassEx(BoolConstant<val>());//创建一个临时对象
}
void AClassEx(TrueType) {
T tmpa = 15;
}
void AClassEx(FalseType) {
T tmpa = "abc";
}
//当为ture时只会去编译重载版本的TureType
};
}
nmsp1::AClass<int, true> tmpobj1;
//如果是第一条注释的if语句会报const char[4]无法转换为int
nmsp1::AClass<string, false> tmpobj2;
//如果是第一条注释的if语句会报无法从int转换为string
编译器设计时的考量,编译器是能够在编译器时期判断出来执行AClass类模板构造函数的哪个分支的,但从编译出代码这个角度来说,不管是哪个条件分支都会去编译,那么编译false分支就会报错.
if constexpr:属于编译期间if语句,可以解决上面
角度来说,不管是哪个条件分支都会去编译,那么编译false分支就会报错.
if constexpr:属于编译期间if语句,可以解决上面