3 回答

TA貢獻1793條經(jīng)驗 獲得超6個贊
是的,這是可能的。一種做到這一點的方法(即使在最近的noexcept更改中也有效)是利用C ++ 11縮小轉(zhuǎn)換規(guī)則:
甲縮小轉(zhuǎn)換為一個整數(shù)型或無作用域枚舉類型為整數(shù)類型不能表示原始類型的所有值的隱式轉(zhuǎn)換[...],除非源是一個常量表達式,其值后積分優(yōu)惠將適合進入目標(biāo)類型。
(強調(diào)我的)。列表初始化通常不允許縮小轉(zhuǎn)換范圍,與SFINAE結(jié)合使用時,我們可以構(gòu)建小工具來檢測任意表達式是否為常量表達式:
// p() here could be anything
template<int (*p)()> std::true_type is_constexpr_impl(decltype(int{(p(), 0U)}));
template<int (*p)()> std::false_type is_constexpr_impl(...);
template<int (*p)()> using is_constexpr = decltype(is_constexpr_impl<p>(0));
constexpr int f() { return 0; }
int g() { return 0; }
static_assert(is_constexpr<f>());
static_assert(!is_constexpr<g>());
現(xiàn)場演示。
此處的關(guān)鍵是int{(expr, 0U)}包含從unsigned int到的變窄轉(zhuǎn)換int(因此格式不正確),除非它 expr是一個常量表達式,在這種情況下,整個表達式(expr, 0U)都是一個常量表達式,其求值適合于type int。
- 3 回答
- 0 關(guān)注
- 515 瀏覽
添加回答
舉報