c++ rvalue reference and const qualifier

前端 未结 2 628
温柔的废话
温柔的废话 2021-02-02 14:29

Among the many benefits of const qualification is to make an API more understandable, example:

template int function1(T const& in);
// clea         


        
2条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-02 14:39

    You could say this:

    template 
    typename std::enable_if::value, int>::type
    function(T && in)
    {
       // ...
    }
    

    where you have something like:

    template  struct immutable
    : std::integral_constant::value> {};
    
    template  struct immutable
    : std::true_type {};
    

    This way, the template will only be usable if the universal reference is either a const-reference (so T = U const &) or an rvalue-reference (so T is not a reference).


    That said, if the argument is not going to be changed, you could just use T const & and be done with it, since there's nothing to be gained from binding mutably to temporary values.

提交回复
热议问题