如何转发左值参考?

时间:2016-04-26 03:16:50

标签: c++11 pass-by-reference perfect-forwarding forwarding-reference

我有这段代码:

struct MultiMemoizator {
    template <typename ReturnType, typename... Args>
    ReturnType callFunction(std::function<ReturnType(Args...)> memFunc, const Args&... args) {
         return memFunc(args ...);
    }
};

int main()
{
    typedef vector<double> vecD;
    //filling vecD with random numbers...
    MultiMemoizator mem;
    function<vecD(vecD)> sort_vec = [](vecD &vec) {
        sort(vec.begin(),vec.end());
        return vec;
    };
    mem.callFunction<vecD,vecD>(sort_vec,vec);
    //vec is still not sorted!
}

由于memFunc(args ...);发生的情况是args的副本已排序而非vec,因此在vec之后callFunction(...)将排除forward

我认为,为了解决这个问题return cachedFunc(forward<Args>(args) ...);可以帮助我,但是如果我尝试:vector::size=0那么就会发生一些不好的事情(比如args)。

如何将sort_vec引用转发给 <div id="mycarousel" class="carousel slide" data-ride="carousel"> <!-- Indicators --> <ol class="carousel-indicators"> <li data-target="#mycarousel" data-slide-to="0" class="active"></li> <li data-target="#mycarousel" data-slide-to="1"></li> <li data-target="#mycarousel" data-slide-to="2"></li> <li data-target="#mycarousel" data-slide-to="3"></li> <li data-target="#mycarousel" data-slide-to="4"></li> </ol> <!-- Wrapper for slides --> <div class="carousel-inner" role="listbox"> <div class="active item"> <%= image_tag("Chess.png", :alt => "chess") %> </div> <% @outings.each do |outing| %> <div class="item"> <%= image_tag outing.image.url(:medium) %> </div> <% end %> </div> <!-- Controls --> <a class="left carousel-control" href="#mycarousel" role="button" data-slide="prev"> <span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span> </a> <a class="right carousel-control" href="#mycarousel" role="button" data-slide="next"> <span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span> </a> </div>

1 个答案:

答案 0 :(得分:1)

将返回类型指定为Type&const Type&并返回不是临时值的内容。 像这样:

function<vecD&(vecD&)> sort_vec = [](vecD &vec) -> vecD& {
    std::sort(vec.begin(),vec.end());
    return vec;
};

P.S。你试图对const向量进行排序。