我試圖在模板函式中的編譯時確定型別 T 是原始型別還是具有底層原始型別的列舉。
在代碼中,我正在嘗試這樣做
template <typename T>
bool foo(T& input)
{
bool isPrimitive = std::is_fundamental<T>::value || (std::is_enum<T>::value && std::is_fundamental<std::underlying_type<T>::type>::value);
// We want to do things using isPrimitive, but not important so omitted.
return isPrimitive; //return this value just to avoid warnings.
}
當呼叫 foo 且 T 不是列舉時,編譯失敗,因為std::underlying_type<T>::type在這種情況下不存在。
enum class Bar : int
{
DUMMYCASE,
};
int main()
{
int test1;
Bar test2;
foo(test1); // fails
foo(test2); // ok
}
我查看了 std::conditional 和 std::enable_if,以及這個答案SFINAE not occur with std::underlying_type但看不到如何做到這一點。似乎 enable_if 僅適用于模板引數。
當 T 不是列舉時,如何重寫該行以便編譯?理想情況下,我想避免更改函式簽名。
bool isPrimitive = std::is_fundamental<T>::value || (std::is_enum<T>::value && std::is_fundamental<std::underlying_type<T>::type>::value);
uj5u.com熱心網友回復:
除了列舉僅支持整數型別之外,您還可以撰寫:
template <typename T>
bool foo(T& input)
{
constexpr bool isPrimitive = [](){
if constexpr (std::is_fundamental_v<T>){
return true;
}
if constexpr (std::is_enum_v<T>){
using underlying_type = typename std::underlying_type<T>::type;
if constexpr (std::is_fundamental_v<underlying_type>){
return true;
}
}
return false;
}();
// We want to do things using isPrimitive, but not important so omitted.
return isPrimitive; //return this value just to avoid warnings.
}
您的代碼的問題是,std::underlying_type 也被實體化為非列舉。此外,還缺少一個型別名消歧器。
std::underlying_type<T>::type是一個依賴名稱,必須以“typename”為前綴 - 否則編譯器假定為非型別。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/508349.html
上一篇:在類定義與類實體化中分配類變數
