如何使用const限定符与decltype

How to use const qualifier with decltype?

本文关键字:decltype 何使用 const      更新时间:2023-10-16

如何将const限定符与decltype用于模板-ed函数?

当前GCC 拒绝以下命令:

template <typename It>
bool process(It first , It last )
{
  return  std::all_of( first, last, 
                       [](  const decltype(*first)& i )
                       //   ^^^^^ without const it works fine
                       { 
                            return i % 2 == 0; 
                       } 
                     ) ;
}

在lambda内部使用i作为const引用是否合法/可能?

const decltype(*first)&不工作,因为decltype(*first)int&,但您希望它是int。您可以使用std::remove_reference来解决这个问题(尽管它并没有真正使代码更清晰):const std::remove_reference<decltype(*first)>::type&

直接解析std::iterator_traits:

#include <algorithm>
#include <iterator>
template <typename It>
bool process(It first , It last )
{
    typedef typename std::iterator_traits<It>::value_type value_type;
    return std::all_of(first, last, []( const value_type& i ) {
        return i % 2 == 0;
    });
}
int main(void) {
    std::vector<int> v = { 0, 2, 4 };
    process(v.begin(), v.end());
}

或者不带iterator_traits:

typedef typename std::decay<decltype(*first)>::type value_type;
const限定符对于引用来说是毫无意义的,并且const decltype(*first)&)给出了具有不可变参数的错误承诺,而该参数实际上是可变的。

你可以add_const:

template <typename It>
bool process(It first , It last )
{
  // std::cout << "Typeid :" << typeid( const decltype(*begin) &).name( ) << 'n' ;
  return  std::all_of( first, last, 
                       [](  typename add_const<decltype(*first)>::type &i )
                       { //          ^^^^^^^^^               
                            return i % 2 == 0; 
                       } 
                     ) ;
}