- 作者: 雪山肥魚
- 時間:20220217 07:51
- 目的: true_type and false_type
# ture_type 簡介
# true_type 與 true 的區(qū)別
true_type 簡介
#include <iostream>
/*
//兩個類型(類模板)
很明顯true_type false_type 是類模板被實例化了的類型
using true_type = integer_constant<bool, true>;
using false_type = integer_constant<bool, false>;
*/
int main(int argc, char **argv) {
return 0;
}
true_type 與true的區(qū)別
true_type :代表類型(類類型)
ture:代表的是值
true_type func(); //可以
true func();//不可以
注意與bool的區(qū)別:
bool 可代表 true false
true_type 只能代表 ture
template<bool var>
struct BoolConstant {
using type = BoolConstant;//寫成 using type = BoolConstant<val>也行
static constexpr bool value = val;
};
using TrueType = BoolConstant<true>;
using FalseType = BoolConstant<false>;
int main(int argc, char **argv) {
return 0;
}
- TrueType(std::true_type) 是一個被實例化的類模板恋昼,即一個類 類型抵屿。代表true的含義忠聚。
- 一般是當(dāng)基類被繼承襟沮,子類也就具備了真或假的意味适室。
比如 is_pointer, is_union,is_function等類模板都是繼承BoolConstant<true>
is_union<int>::value
- 可以當(dāng)作一種返回類型被使用
后續(xù)萃取使用
FalseType myfunc1();//返回真
TrueType myfunc2();// 返回假
舉例:
using TrueType = BoolConstant<true>;
using FalseType = BoolConstant<false>;
template <typename T, bool val>
struct AClass {
AClass() {
cout << "AClass:AClass()執(zhí)行了" << endl;
if (val) {
T tmpa = 15;
}
else {
T tmpa = "abc"
}
}
};
int main(int argc, char **argv) {
AClass<int, true> tmpobj1;
//AClass<string, false> tmpobj2;
return 0;
}
上述代碼看上去沒有問題,實則不能通過編譯鸥拧。
如果是int茉稠,int tmpa = "abc",是明顯有問題的。
1>c:\users\liush\desktop\template\ture_typeandfalse_type\main.cpp(29): error C2440: “初始化”: 無法從“const char [4]”轉(zhuǎn)換為“T”
1> with
1> [
1> T=int
1> ]
解決方案1:
用 if constexpr
template <typename T, bool val>
struct AClass {
AClass() {
cout << "AClass:AClass()執(zhí)行了" << endl;
if constexpr (val) {
T tmpa = 15;
}
else {
T tmpa = "abc";
}
}
};
int main(int argc, char **argv) {
AClass<int, true> tmpobj1;
//AClass<string, false> tmpobj2;
return 0;
}
解決方案2:truetype falsetype 簡單應(yīng)用
template<bool var>
struct BoolConstant {
using type = BoolConstant;//寫成 using type = BoolConstant<val>也行
static constexpr bool value = var;
};
using TrueType = BoolConstant<true>;
using FalseType = BoolConstant<false>;
template <typename T, bool val>
struct AClass {
AClass() {
cout << "AClass:AClass()執(zhí)行了" << endl;
/*
if constexpr (val) {
T tmpa = 15;
}
else {
T tmpa = "abc";
}
*/
//AClassEx 是成員函數(shù)
AClassEx(BoolConstant<val>());//BoolConstant<val>() 創(chuàng)建臨時對象
}
void AClassEx(TrueType abc) {
cout << "AClassEx(TrueType abc)" << endl;
T tmpa = 15;
}
void AClassEx(FalseType abc) {
cout << "AClassEx(FalseType abc)" << endl;
T tmpa = "abc";
}
};
int main(int argc, char **argv) {
AClass<int, true> tmpobj1;
AClass<string, false> tmpobj2;
return 0;
}