如何使用const限定符与decltype
How to use const qualifier with decltype?
如何将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;
}
) ;
}
相关文章:
- 在VS2010-VS2015下编译时,如何使用decltype作为较大类型表达式的LHS
- 在for循环中使用auto vs decltype(vec.size())来处理字符串的向量
- 是否可以在不使用 decltype 的情况下推断先前定义的 extern 变量的类型
- 我可以使用 decltype() 或其他东西通过指针获取真实类型吗?
- decltype:使用指针访问类的静态成员
- 在部分模板专用化中使用 decltype
- 是否可以使用单个定义定义函数的常量和常规版本?(使用模板,自动,decltype等)
- 使用具有默认参数的函数模板进行 decltype 会使结果混乱(一个有趣的问题或 gcc 的错误)
- 如何在私有类成员上使用 decltype?
- 如何使用 decltype 获取没有引用的指针?
- 使用 AppleClang 时来自 decltype( std::d evlcal<std::ostream>() << std::d eclval<T>() 的奇
- 在扣除自动之前使用decltype(auto) <func>
- 元函数使用 decltype 返回元素类型
- 在 decltype 中使用命名空间
- 使用 decltype(this) 获取函数引用
- 使用像typedef这样的decltype
- 使用“decltype”获取迭代器的类型
- 我可以在没有任何实例变量的情况下使用 decltype 吗?
- 在 decltype 中使用 this 指针
- 奇怪的操作符?:与decltype一起使用