您现在的位置: 首页 > 网站导航收录 > 百科知识百科知识
你见过哪些令你瞠目结舌的C/C++代码技巧?
静态,代码,字节你见过哪些令你瞠目结舌的C/C++代码技巧?
发布时间:2019-02-08加入收藏来源:互联网点击:
你见过哪些令你瞠目结舌的C/C++代码技巧?
回答于 2019-09-11 08:43:50
回答于 2019-09-11 08:43:50
手持两把锟斤拷,
口中疾呼烫烫烫。
脚踏千朵屯屯屯,
笑看万物锘锘锘。
回答于 2019-09-11 08:43:50
字节按位逆序:
unsigned char b; // 要反转的字节
b = (b * 0x0202020202ULL & 0x010884422010ULL) % 1023;
省去了循环
回答于 2019-09-11 08:43:50
有两段利用编译器报错实现静态检查的代码
第一段来自Modern C++ Design--Generic Programming and Design Patterns Applied
template<bool> struct CompileTimeChecker
{
CompileTimeChecker(...);
};
template<> struct CompileTimeChecker<false> { };
#define STATIC_CHECK(expr, msg) \
{\
class ERROR_##msg {}; \
(void)sizeof(CompileTimeChecker<(expr) != 0>((ERROR_##msg())));\
}
应用
template <class To, class From>
To safe_reinterpret_cast(From from)
{
STATIC_CHECK(sizeof(From) <= sizeof(To),
Destination_Type_Too_Narrow);
return reinterpret_cast<To>(from);
}
第一段来自SGI STL 对模板接口(concept)静态检查的宏
#define __STL_REQUIRES_BINARY_OP(__opname, __ret, __first, __second) \
do { \
__ret (*__x)( __first&, __second& ) = _STL_BINARY##__opname##_ERROR< \
__ret, __first, __second>::__binary_operator_requirement_violation; \
__ret (*__y)( const __first&, const __second& ) = \
_STL_BINARY##__opname##_ERROR< __ret, __first, __second>:: \
__const_binary_operator_requirement_violation; \
__y = __y; __x = __x; } while (0)
// Use this to check whether type X is convertible to type Y
#define __STL_CONVERTIBLE(__type_x, __type_y) \
do { \
void (*__x)( __type_x , __type_y ) = _STL_CONVERT_ERROR< __type_x , \
__type_y >::__type_X_is_not_convertible_to_type_Y; \
__x = __x; } while (0)
应用
template <class _InputIter, class _Tp>
inline _InputIter find(_InputIter __first, _InputIter __last,
const _Tp& __val)
{
__STL_REQUIRES(_InputIter, _InputIterator);
__STL_REQUIRES_BINARY_OP(_OP_EQUAL, bool,
typename iterator_traits<_InputIter>::value_type, _Tp);
return find(__first, __last, __val, __ITERATOR_CATEGORY(__first));
}
里面关于concept的部分代码不少,这个思路很好。现代配合static_assert可以实现提示信息更加强的静态检查了
回答于 2019-09-11 08:43:50
复制+粘贴最省时 但同时也是最把你最快带入这个学习的节奏。
csdn,百度文库通通利用起来
各种程序员经验刷起来
借鉴别人的才能写出好多西
多看多写多用,程序员工资高肯定是有硬道理的。
希望对你有帮助[玫瑰]
上一篇:有哪些令你惊艳的窗帘设计?
下一篇:返回列表
相关链接 |
||
网友回复(共有 0 条回复) |