c++ tricks

1 C++ Write a function that uses the specialization of the template function to get the length of an array.

#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 is automatically generated

Implemented by macro definition

#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;

Example of use:

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

generation

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

3 inline keyword

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 Release the storage space of the vector

The source code of reverse, you can see that when reserve(0), there is no logic to release excess space

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 Iteration of the macro itself

#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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324123447&siteId=291194637