Default function that just returns the passed value?

前端 未结 6 1475
礼貌的吻别
礼貌的吻别 2020-12-31 08:24

As a lazy developer, I like to use this trick to specify a default function:

template 

        
6条回答
  •  一整个雨季
    2020-12-31 09:14

    This is called the identity function. Unfortunately, it is not part of the C++ standard, but you can easily build one yourself.


    If you happen to use g++, you can activate its extensions with -std=gnu++11 and then

    #include 
    #include 
    
    template  >
    void index(std::array &x, Function&& f = Function())
    {
        for (unsigned int i = 0; i < Size; ++i) {
            x[i] = f(i);
        }
    }
    

    Maybe it will be available in C++20, see std::identity. Until then you may look at boost's version at boost::compute::identity.

提交回复
热议问题