简体   繁体   English

如何将const限定符与decltype一起使用?

[英]How to use const qualifier with decltype?

How do I use const qualifier with decltype for template -ed function ? 如何将const限定符与decltype用于模板 -ed函数?

Current GCC rejects following : 目前的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; 
                       } 
                     ) ;
}

Is it legal/possible to use i as const reference inside the lambda ? 在lambda中使用i作为const引用是合法/可能的吗?

const decltype(*first)& doesn't work because decltype(*first) is int& , but you expect it to be int . const decltype(*first)&不起作用,因为decltype(*first)int& ,但你希望它是int You can use std::remove_reference to work around that (although it doesn't really make the code clearer): const std::remove_reference<decltype(*first)>::type& 您可以使用std::remove_reference来解决这个问题(虽然它并没有真正使代码更清晰): const std::remove_reference<decltype(*first)>::type&

Just resolve to std::iterator_traits: 只需解析为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());
}

Or without iterator_traits: 或者没有iterator_traits:

typedef typename std::decay<decltype(*first)>::type value_type;

Which leads to: A const qualifier is pointless for a reference and the const decltype(*first)&) is giving a false promise of having an immutable argument, which is actually mutable. 这导致:const限定符对于引用是没有意义的,并且const decltype(*first)&)给出了具有不可变参数的错误承诺,其实际上是可变的。

You could add_const : 你可以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; 
                       } 
                     ) ;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM