constexpr
#define assert_static(e) do{ enum{ assert_static__ = 1 / (e) }; } while(0)
template<typename T, typename U>
int bit_copy(T& a, U& b) {
assert_static(sizeof(a) == sizeof(b));
return 7;
}
int main() {
int a = 0x2468;
double b;
bit_copy(a, b);
}
基于这个特性,constexpr还可以被用来实现编译期的type traits,比如STL中的is_const的完整实现:
作者:0x55aa
链接:https://www.jianshu.com/p/34a2a79ea947
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
template<class _Ty,
_Ty _Val>
struct integral_constant
{ // convenient template for integral constant types
static constexpr _Ty value = _Val;
typedef _Ty value_type;
typedef integral_constant<_Ty, _Val> type;
constexpr operator value_type() const noexcept
{ // return stored value
return (value);
}
constexpr value_type operator()() const noexcept
{ // return stored value
return (value);
}
};
typedef integral_constant<bool, true> true_type;
typedef integral_constant<bool, false> false_type;
template<class _Ty>
struct is_const
: false_type
{ // determine whether _Ty is const qualified
};
template<class _Ty>
struct is_const<const _Ty>
: true_type
{ // determine whether _Ty is const qualified
};
int main() {
bool b=false;
//static_assert (b, "efa");
//static_assert(is_const<int>::value,"error");//error
constexpr auto e = true_type()();
is_const<const int> mm ;
static_assert (mm(), "ca");
static_assert (e, "ef");
static_assert (true_type()(), "ef");
static_assert (is_const<const int>(), "ef");
static_assert(is_const<const int>::value, "error");//ok
return 0;
}