业余整理的工作笔记

C++拾遗

2020-04-20  本文已影响0人  龙遁流
可变参数模板函数
template <typename ...T>
void f(T... args)
{
    cout << sizeof...(args) <<endl;
}
省略号的作用
参数包展开
可变参数模板类
template<class ...Args>
class tuple;
模板递归和特化方式展开参数包
//类声明
template <typename ...Args> 
struct Sum;
//递归展开
template <typename First, typename ...Rest>
struct Sum<First, Rest...>
{
    enum
    {
        value = Sum<First>::value + Sum<Rest...>::value
    };
}
//递归终止
template <typename Last>
struct Sum<Last>
{
    enum
    {
        value = sizeof(Last)
    };
}

使用 std::integral_constant消除枚举定义value ,上例可修改为

template <typename ...Args>
struct Sum;

template <typename First, typename ...Rest>
struct Sum<First, Rest...> :
    std::integral_constant<int, Sum<First>::value + Sum<Rest...>::value>
{
}

template <typename Last>
struct Sum<Last> : 
    std::integral_constant<int, sizeof(Last)>
{
}

Sum<int, double, short>::value;
继承方式展开参数包

内存对齐的缓冲区
template <std::size_t Len, std::size_t Align = /*default-alignment*/>
struct aligned_storage;
使用
struct A
{
    int avg;    
}
using Aligned_A = std::aligned_storage<sizeof(A), std::alignment_of<A>::value>::type;
int main()
{
    Aligned_A a, b;
    new (&a) A();
    b = a;
    cout << reinterpret_cast<A&>(b).avg<<endl;
    
    return 0;
}

可变模板参数和type_taits综合应用
template <typename T>
class Task;

template<typename R, typename ...Args>
class Task<R(Args...)>
{
    public:
        Task(std::function<R(Args...)> &&f) : m_fn(std::move(f)){}
        Task(std::function<R(Args...)> &f) : m_fn(f){}
        
        R Run(Args&&... args)
        {
            return m_fn(std::forward<Args>(args)...);
        }
        
        template<typename F>
        auto Then(F &&f) -> Task<typename std::result_of<F(R)>::type(Args...)>
        {
            using return_type = typename std::result_of<F(R)>::type;
            auto func = std::move(m_fn);
            return Task<return_type(Args...)>([func, &f] (Args&&... args)
            {
                return f(func(std::forward<Args>(args)...));
            };
        }
    private:
        std::function<R(Args...)> m_fn;
}

{
Task<int(int)> task([](int i){return i});
auto result = task.Then([](int i){return i + 1})
                  .Then([](int i){return i + 2})
                  .Then([](int i){return i + 3})
                  .Run(1);
}

上一篇下一篇

猜你喜欢

热点阅读