Default function that just returns the passed value?

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

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

template 

        
6条回答
  •  旧时难觅i
    2020-12-31 09:02

    A way to deal with this is to have two different functions. I find quite sane not to use default parameters.

    template 
    void index(std::array &x, Function&& f){
        for(unsigned int i = 0; i < Size; ++i) x[i] = f(i);
    }
    
    template
    void index(std::array &x){
        return index(x, [](unsigned int i){return i;});                      // C++11 in this case
                    //, [](auto&& e){return std::forward(e)};); // C++14 in a more general case
                    //, std::identity); // C++20 in general
    }
    

提交回复
热议问题