c++奇技淫巧

1 C++ 写一个函数,用模板函数的特例化这个属性得到一个数组的长度。

#include <iostream>
using namespace std;
 
template <typename Type, size_t N>
inline size_t GetArrayLength(const Type(&)[N])
{
    return N;
}
 
void main()
{
    int a []= {,,};
    cout << GetArrayLength(a) << endl;
    system("pause");
}

2 get/set自动生成

通过宏定义来实现

#define ClassVar(permission, type, name, value, funcname)       \
    public:                                                     \
        void Set##funcname(type v_val) { name = v_val; }        \
        type Get##funcname() const { return name; }             \
    permission:                                                 \
        type name = value;

使用例子:

ClassVar(private, int, cnt_, 0, Count)

生成

public:
    void SetCount(int v_val) { cnt_ = v_val; }
    int GetCount() const { return cnt_; }
private:
    int cnt_ = 0;

3 inline(内联)关键字

inline int max(int a, int b)     
    return a > b ? a : b                         
}                                
                                           
int main()                                  
{                                         
    int a, b, c;                           
    cin >> a >> b >> c;                   
                                           
    cout << max(a, b) << endl;  
    return 0;                            
}  

4 释放vector的存储空间

reverse的源代码,可以看到当reserve(0)时,并没有释放多余空间的逻辑

template 
void
vector<_Tp, _Allocator>::reserve(size_type __n)
{
 if (__n > capacity())
 {
 allocator_type& __a = this->__alloc();
 __split_buffer __v(__n, size(), __a);
 __swap_out_circular_buffer(__v);
 }
}

5 宏自身迭代

#define BOOST_PP_COMMA_IF(cond) BOOST_PP_IF(cond, BOOST_PP_COMMA, BOOST_PP_EMPTY)()
#define BOOST_PP_IF(cond, t, f) BOOST_PP_IIF(BOOST_PP_BOOL(cond), t, f)
#define BOOST_PP_IIF(bit, t, f) BOOST_PP_IIF_I(bit, t, f)
#define BOOST_PP_IIF_I(bit, t, f) BOOST_PP_IIF_ ## bit(t, f)
# define BOOST_PP_IIF_0(t, f) f
# define BOOST_PP_IIF_1(t, f) t
#define BOOST_PP_BOOL(x) BOOST_PP_BOOL_I(x)
# define BOOST_PP_BOOL_I(x) BOOST_PP_BOOL_ ## x
# define BOOST_PP_BOOL_0 0
# define BOOST_PP_BOOL_1 1
# define BOOST_PP_BOOL_2 1
... ...
# define BOOST_PP_BOOL_256 1

猜你喜欢

转载自blog.csdn.net/weixin_41055260/article/details/123634038