Is it possible to develop static for loop in c++?

前端 未结 4 1496
情歌与酒
情歌与酒 2020-12-04 13:44

Is it possible for something like this to exist?

template
void deduce_mask(Matrix const &src, int mask[])
{
    //I hope i could b         


        
4条回答
  •  执念已碎
    2020-12-04 14:26

    Template metaprogramming in C++ is pure functional programming, and in pure functional programming you don't get to use loops like for or while and you don't get to have any mutable data at all. All you have is recursion. To make working with recursion easier, you need to rise abstraction level a bit. The recursive code that you have is fine, but the iteration and work can be split apart:

    template 
    struct static_for
    {
        template 
        void operator()(Fn const& fn) const
        {
            if (First < Last)
            {
                fn(First);
                static_for()(fn);
            }
        }
    };
    
    template 
    struct static_for
    {
        template 
        void operator()(Fn const& fn) const
        { }
    };
    

    Now that you have this meta-function, you can write your deduce_mask function like this:

    template
    void deduce_mask(Matrix const &src, int mask[])
    {
        static_for<0, Channel>()([&](int i)
        {            
            mask[mapper(0, 1, i)] = src(row - 1, col)[i];
            mask[mapper(1, 1, i)] = src(row, col)[i];
            mask[mapper(2, 1, i)] = src(row + 1, col)[i];    
        });
    }
    

    Visual C++ 2012 with /Ob1 command line switch compiles this code into this:

    push        0  
    call        ::operator() (010C1270h)  
    push        1  
    call        ::operator() (010C1270h)  
    push        2  
    call        ::operator() (010C1270h)  
    push        3  
    call        ::operator() (010C1270h)  
    push        4  
    call        ::operator() (010C1270h)  
    ...
    

    If you can't use lambda functions, you need to write a functor. Functor has one advantage over lambda function - you can specify a calling convention (if you don't mind doing that). If the operator() of the functor has __fastcall calling convention then you will see mov edx, x instead of push x in the assembler code.

提交回复
热议问题